我的观点:
class HospitalDoctorAddView(CreateView):
template_name = "hospital_doctor_add.html"
form_class = HospitalDoctorInfoForm
model = HospitalDoctor
success_url = "/hospital-profile/"
def get_context_data(self, **kwargs):
context = super(HospitalDoctorAddView, self).get_context_data(**kwargs)
context['formset'] = TimingFormSet
return context
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
formset = TimingFormSet(request.POST, prefix='timing')
if form.is_valid() and formset.is_valid():
self.form_save(form)
self.formset_save(formset)
return render(request, self.template_name, {
'form': HospitalDoctorInfoForm,
'formset': formset})
def form_save(self, form):
info = HospitalDoctor()
info.hospital = self.request.user
info.full_name = form.cleaned_data['full_name']
info.expertization = form.cleaned_data['expertization']
info.nmc_no = form.cleaned_data['nmc_no']
info.save()
def formset_save(self, form):
frm = Timing()
frm.day = form.cleaned_data['day']
frm.mng_start = form.cleaned_data['mng_start']
frm.mng_end = form.cleaned_data['mng_end']
frm.eve_start = form.cleaned_data['eve_start']
frm.eve_end = form.cleaned_data['eve_end']
frm.save()
并在我的模板中:
<form method="post" action="">{% csrf_token %}
<p>{{form}}</p>
<p>{{formset.management_form}}</p>
<table>
{% for form in formset %}
{{form}}
{% endfor %}
</table>
<input type="submit" value="Create" />
</form>
我想发布常规表单和formset。
我在这里得到ValidationError:您的ManagementForm数据丢失或被篡改过了#39;。我不知道什么是错的。需要帮助。
答案 0 :(得分:0)
试试这个,看看会发生什么:
def get_context_data(self, **kwargs):
context = super(HospitalDoctorAddView, self).get_context_data(**kwargs)
if self.request.POST
context['formset'] = TimingFormSet(self.request.POST, prefix='timing')
return context
def post(self, request, *args, **kwargs):
form = self.get_form(self.get_form_class())
formset = TimingFormSet(request.POST, prefix='timing')
if form.is_valid() and formset.is_valid():
self.form_save(form)
self.formset_save(formset)
print(self.get_context_data(**kwargs)) # See what is being passed in the context
return render(request, self.template_name, self.get_context_data(**kwargs))
您希望将CBV的完整上下文传递给模板,而在传递表单类的名称之前。