我有一个医生详细信息视图,其中我已将表单作为上下文传递:
class HospitalDoctorDetailView(DetailView):
context = {}
model = HospitalDoctor
template_name = "hospital_doctor_detail.html"
context_object_name = 'doctor'
def get_context_data(self, **kwargs):
context = super(HospitalDoctorDetailView, self).get_context_data(**kwargs)
context['appointment_form'] = AppointmentForm1
return context
我在名为hospital_doctor_detail.html
的模板中使用了此表单:
<form action="/appointment/{{doctor.id}}/{{doctor.hospital.id}}/" method="post">{% csrf_token %}
First Name:<br/>
{{ form.first_name.errors }}
{{ appointment_form.first_name }}<br/>
Middle Nmae:<br/>
{{ form.middle_name.errors }}
{{ appointment_form.middle_name }}<br/>
Last Name:<br/>
{{ form.last_name.errors }}
{{appointment_form.last_name}}<br/>
Age:<br/>
{{ form.age.errors }}
{{ appointment_form.age }}<br/>
Date:<br/>
{{ form.appointment_date.errors }}
{{ appointment_form.appointment_date }}<br/>
<br/>
<input type="submit" value="Take Appointment" style="background-color:#EFEFEF; border:1px solid #000;" />
</form>
我的表单AppointmentForm1是一个模型表单。要提交表格,我写了一个观点:
def TakeAppointmentView(request, pk, hpk):
doctor = HospitalDoctor.objects.get(pk=pk)
hospital = Hospital.objects.get(pk=hpk)
if request.method == "POST":
form = AppointmentForm1(request.POST)
if form.is_valid():
app = DoctorAppointment()
app.user = request.user
app.doctor = doctor
app.hospital = hospital
app.first_name = form.cleaned_data['first_name']
app.middle_name = form.cleaned_data['middle_name']
app.last_name = form.cleaned_data['last_name']
app.age = form.cleaned_data['age']
app.appointment_date = form.cleaned_data['appointment_date']
app.save()
messages.success(request, "Thank you for taking appointment")
return redirect("doctor_detail", pk)
#return redirect("/home/")
else:
return render_to_response("hospital_doctor_detail.html", {"appointment_form":form}, context_instance=RequestContext(request))
else:
form = AppointmentForm1()
return render_to_response("hospital_doctor_detail.html", {"appointment_form":form}, context_instance=RequestContext(request))
如果表格有效,则预约成功,但如果表格无效,我想将其重定向到同一医生详细信息视图。
这里我收到一个错误,如果表单无效,它会重定向到医生详细信息视图并显示错误消息,但不显示表单? 这里有什么不对吗?
答案 0 :(得分:2)
您将表单作为{"application_form": form}
返回到模板。
你的模板对任何名为form
的变量一无所知。
而不是使用:
{{ form.first_name.errors }}
尝试对每条错误消息使用以下内容:
{{ application_form.first_name.errors }}