我正在使用Django构建应用程序,当InlineFormSet
与ClassBasedViews
一起使用时,我的route_formset
在模板中为空,但form
填充了数据,因为它应该是。
我做错了什么?
查看
class ReservationUpdateView(UpdateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_form_kwargs(self):
kwargs = super(ReservationUpdateView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates versions of the form
and its inline formsets.
"""
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
route_formset = RouteFormSet()
return self.render_to_response(
self.get_context_data(form=form,
route_formset=route_formset))
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance and its inline
formsets with the passed POST variables and then checking them for
validity.
"""
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
route_formset = RouteFormSet(self.request.POST)
if (form.is_valid() and route_formset.is_valid()):
return self.form_valid(form, route_formset)
else:
return self.form_invalid(form, route_formset)
def form_valid(self, form, route_formset):
"""
Called if all forms are valid. Creates a Recipe instance along with
associated Ingredients and Instructions and then redirects to a
success page.
"""
self.object = form.save()
route_formset.instance = self.object
route_formset.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, route_formset):
"""
Called if a form is invalid. Re-renders the context data with the
data-filled forms and errors.
"""
return self.render_to_response(
self.get_context_data(form=form,
route_formset=route_formset))
模板
{% for form in route_formset %}
<div class="form-group">
<label class="col-sm-3 control-label">Time / Place</label>
<div class="col-sm-2">
{{ form.time }}
</div>
<div class="col-sm-5">
{{ form.place }}
</div>
</div>
{% endfor %}
表单集
RouteFormSet = inlineformset_factory(Reservation, Stop, fields=('time','place'), extra=2)
因此,formset应该填充Stops
,但它是空的..
答案 0 :(得分:1)
尝试使用实例初始化formset以使用相关数据填充它:
route_formset = RouteFormSet(instance=self.object)