视图___没有返回HttpResponse对象。它返回None

时间:2019-04-11 16:52:23

标签: django django-forms django-templates django-views

我有一个计划应用程序,病人可以在此注册约会。当我提交新约会的表格时,出现值错误。

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 个答案:

答案 0 :(得分:3)

您的视图必须始终返回HTTP响应。目前,您的代码无法处理request.method == 'POST'时的情况,但是格式无效。

您可以通过缩进最后的return语句,将其移到else块之外来修复代码:

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})