Saturday, April 1, 2017

Form is invalid even when all fields are correct? Tried to check with fields.error but I got none, so I removed it.

  As mentioned above, I am trying to figure out why my code isn't saving a form even though it is valid. My code right now looks like this:

Views:

@login_required
@csrf_exempt
def profile(request):
"""
Where the profile information is being rendered
"""

docs2 = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('specialization')
pats2 = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('DoB')
nurs2 = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('salary')

pat = dict()
nur = dict()
doc = dict()

if request.method == 'POST':
# This activates if there's actually some data sent with the post, i.e
# the form was filled out, so let's go to profile_update.
# The reason we're checking for it being greater than one is because our buttons
# send out csrftokens with their requests, so there's always at least one thing in
# the request.POST's QueryDict
if len(request.POST) > 1:
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('/accounts/dashboard')
else:
return HttpResponse('Error: Form was invalid!')
# This happens otherwise, i.e. load that empty form
else:
template = loader.get_template("accounts/profileupdate.html")
pat_form = PatientForm
context = {'form': pat_form}
return HttpResponse(template.render(context, request))

if not nurs2.exists():
if not docs2.exists():
pat['DOB'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('DoB')
pat['FIRST'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('first_name')
pat['SSS'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('SSN')
pat['USERN'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('user')
pat['MIDDLE'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('middle_initial')
pat['LAST'] = Patient.objects.filter(user=User.objects.filter(username=request.user.username)).values('last_name')
return render(request, 'accounts/profile.html', pat)

if not nurs2.exists():
if not pats2.exists():
doc['DOB'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('specialization')
doc['FIRST'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('first_name')
doc['SSS'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('SSN')
doc['USERN'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('user')
doc['MIDDLE'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('middle_initial')
doc['LAST'] = Doctor.objects.filter(user=User.objects.filter(username=request.user.username)).values('last_name')
return render(request, 'accounts/profile.html', doc)

if not docs2.exists():
if not pats2.exists():
nur['DOB'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('salary')
nur['FIRST'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('first_name')
nur['SSS'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('SSN')
nur['USERN'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('user')
nur['MIDDLE'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('middle_initial')
nur['LAST'] = Nurse.objects.filter(user=User.objects.filter(username=request.user.username)).values('last_name')
return render(request, 'accounts/profile.html', nur)
return HttpResponse("Error: You are not a Patient, Doctor or Nurse!")


FORM.py:

class PatientForm(ModelForm):
"""
A form for registering a Patient model from the Django built-in auth model
"""
class Meta:
model = Patient
fields = '__all__' #TODO remove the user having to set their own user field.


Models:


class Patient(models.Model):
"""
The patient model, which contains basic info, emergency contact info,
and their doctor
"""
# Theoretically gives us authentication easily, definitely gives
# us the username, password, and email
user = models.OneToOneField(User, on_delete=models.CASCADE)

# Name info
first_name = models.CharField(default="", max_length=12)
middle_initial = models.CharField(default="", max_length=1)
last_name = models.CharField(default="", max_length=15)

# Location-based info
address = models.CharField(default="", max_length=30) # Could be expanded to have more info

# Personal contact info
cell_num1 = models.IntegerField(
default=0,
unique=True,
validators=[RegexValidator(regex='^\d{10}$', message='Length has to be 10', code='Invalid number')]
)
cell_num2 = models.IntegerField(
default=0,
unique=True,
validators=[RegexValidator(regex='^\d{10}$', message='Length has to be 10', code='Invalid number')]
)

# Should be hashed later; also is the primary key
SSN = models.IntegerField(
default=0,
primary_key=True,
unique=True,
validators=[RegexValidator(regex='^\d{9}$', message='Length has to be 9', code='Invalid number')]
)

def __str__(self): # Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
return str(self.first_name + self.last_name)

# Specializations for Patient

# Emergency contact info; if it's a patient, we need to link to that patient
emergency_first_name = models.CharField(default="", max_length=12)
emergency_mi = models.CharField(default="", max_length=1)
emergency_last_name = models.CharField(default="", max_length=15)
# Phone numbers
emergency_num1 = models.IntegerField(
default=0,
null=True,
unique=True,
validators=[RegexValidator(regex='^\d{10}$', message='Length has to be 10', code='Invalid number')]
)
emergency_num2 = models.IntegerField(
default=0,
unique=True,
null=True,
validators=[RegexValidator(regex='^\d{10}$', message='Length has to be 10', code='Invalid number')]
)

# Their doctor
doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)

# Their hospital
hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE)

# Date of Birth
DoB = models.DateField()

# Insurance info
insurance_groupID = models.IntegerField(default=0) # The ID of the insurance group
insurance_persID = models.IntegerField(default=0)


HTML:

Profile
{% extends 'base.html' %}

{% block body %}

<div class="text-center">
<h3>Here is all of your current information!</h3>
</div>

<h4 style="padding-top: 32px;">&nbsp;{{ FIRST }}</h4>
<br />
<h4 id="MIDD">&nbsp;{{ MIDDLE }}</h4>
<br />
<h4 id="LAST">&nbsp;{{ LAST }}</h4>
<br />
<h4 id="DOB">&nbsp;{{ DOB }}</h4>
<br />
<h4 id="SSN">&nbsp;{{ SSS }}</h4>
<br />
<h4 id="USERNAME">&nbsp;{{ USERN }}</h4>
<br />

<form action ="" method="post">
{% csrf_token %}
<div class="text-center">
<input type="submit" value="Update" class="btn btn-default"/>
</div>
</form>

{% endblock %}

PROFILE UPDATE:

{% extends 'base.html' %}

{% block body %}

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="text-center">
<input type="submit" value="Submit" class="btn btn-default"/>
</div>
</form>

{% endblock %}


BASE:

<html>
{% if user.is_authenticated %}

<h1>&nbsp;HealthNet</h1>
<div class="topnav" id="myTopnav">
<a href="/home">Home</a>
<a href="/accounts/dashboard">Dashboard</a>
<a href="/accounts/appointment">Create/Update Appointment</a>
<a href="/accounts/profile">Profile</a>
<a href="/accounts/contact">Contact</a>
<a href="/accounts/logout">Logout</a>
</div>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">

{% block head %}
<title>HealthNet</title>

{% endblock %}

{% block body %}

{% endblock %}
<style>

h1{
text-decoration: none;
border-bottom: none;
font-size: 48px;
display: block;
color: black;
}
footer{
padding-top: 20px;
}
.topnav {
overflow: hidden;
background-color: #bce8f1;
width: 100%;
}
.topnav a {
float: left;
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
font-weight: bold;
}

.topnav a:hover {
background-color: #ddd;
color: black;
}

.topnav a.active {
background-color: #4CAF50;
color: black;
}

</style>

{% else %}
<h6>You are not logged in. To see this page you must login. To do so, go to the login page at
http://127.0.0.1:8000/accounts/login/</h6>

{% endif %}

</html>


URLS:


urlpatterns = [
url(r'^login', views.patient_login, name='login'),
url(r'^home', views.home_page, name='profile_home'),
url(r'^registration', views.patient_registration, name='registration'),
url(r'^registration2', views.PatView.as_view(), name='registration2'),
url(r'^dashboard', views.index, name='dashboard'),
url(r'^all_events', views.all_events, name='all_events'),
url(r'^profile', views.profile, name='profile'),
url(r'^contact', views.contact, name='contact'),
url(r'^appointment', views.CalView.as_view(), name='appointment'),
url(r'^appointment_cancel', views.appointment_cancel),
url(r'^profile_update', views.profile_update, name='profile_update'),
url(r'^calender', views.CalView.as_view(), name='calView'),
url(r'^logout', views.logaway, name='logout'),
url(r'^error', views.error, name='error')
]


ANY HELP WOULD BE GREATLY APPRECIATED



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/86fdc8c2-7265-4dfd-a541-da2f5f9d9c83%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment