gpt4 book ai didi

python - 表单无效后django上下文表单未呈现

转载 作者:行者123 更新时间:2023-12-01 04:56:17 27 4
gpt4 key购买 nike

我有一个医生详细信息 View ,其中我已将表单作为上下文传递:

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 是一个模型表单。为了提交表单,我编写了一个 View :

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

如果表格有效,预约成功,但如果表格无效,我想将其重定向到同一个医生详细信息 View 。

这里我收到一个错误,如果表单无效,它会重定向到医生详细信息 View 并显示错误消息,但表单不显示?这里有什么问题吗??

最佳答案

您将表单返回到模板,格式为 {"application_form": form}

您的模板对任何名为 form 的变量一无所知。

而不是使用:

{{ form.first_name.errors }}

尝试对每条错误消息使用以下内容:

{{ application_form.first_name.errors }}

关于python - 表单无效后django上下文表单未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com