0
votes

I have a scheduling app where patients can register for appointments. When I submit the form for a new appointment, I get the value error.

views.py

def patient_portal(request):
    appointments = Appointment.objects.filter(patient=request.user.patient.pid)
    data_input = request.GET.get('date')
    selected_date = Appointment.objects.filter(date = data_input).values_list('timeslot', flat=True)
    available_appointments = [(value, time) for value, time in Appointment.TIMESLOT_LIST if value not in selected_date]
    doctor =  Patient.objects.get(doctor=request.user.patient.doctor).doctor
    print(doctor)

    if request.method == 'POST':
        form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient)
        if form.is_valid():
            form.save()
            return redirect('../home/')
    else:
        form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient)
        return render(request, 'scheduling/patient.html', {"form" : form, "appointments" : appointments, "available_appointments" : available_appointments, "data_input": data_input, "doctor": doctor})

patient.html:

<form method="post" action="" id="timeslot" enctype="multipart/form-data">
     {% csrf_token %}
     {{ form|crispy }}
     <button type="submit" class="btn btn-primary">Submit</button>
</form>

forms.py:

class AppointmentForm(forms.ModelForm):
    class Meta:
        model = Appointment
        fields = ('doctor','patient','date','timeslot') 
1
doctor = Patient.objects.get(doctor=request.user.patient.doctor).doctor looks more complicated than it needs to be. Wouldn’t doctor = request.user.patient.doctor work?Alasdair

1 Answers

3
votes

Your view must always return an HTTP response. At the moment, your code doesn't handle the case when request.method == 'POST', but the form is invalid.

You can fix your code by de-indenting the final return statement, to move it outside of the else block:

def patient_portal(request):
    ...
    if request.method == 'POST':
        form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient)
        if form.is_valid():
            form.save()
            return redirect('../home/')
    else:
        form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient)
    return render(request, 'scheduling/patient.html', {"form" : form, "appointments" : appointments, "available_appointments" : available_appointments, "data_input": data_input, "doctor": doctor})