在Django项目中,我有一个视图(云),类型:CreateView.此视图具有inlineformset_factory.有用.但是,如果我提交带有错误的表单(请查看下面的"messages.error"),页面将重定向到project.get_absolute_url().问题是:表单内容回空.我知道那是因为HttpResponseRedirect.
如何在不破坏表格的情况下更改此内容?
views.py
class cloud(CreateView): template_name = 'base/cloud.html' form_class = UserForm def get_context_data(self, **kwargs): context = super(cloud, self).get_context_data(**kwargs) project = get_object_or_404(Project, slug=self.kwargs['slug']) context['project'] = project if self.request.POST: context['formset'] = IdeaFormset(self.request.POST or None) else: context['formset'] = IdeaFormset() return context def form_valid(self, form, **kwargs): project = get_object_or_404(Project, slug=self.kwargs['slug']) context = self.get_context_data() formset = context['formset'] if formset.is_valid(): self.object = form.save() formset.instance = self.object #IdeaFormFormSet nouns = project.nouns().values_list('content', flat=True) verbs = project.verbs().values_list('content', flat=True) error = False for form in formset.forms: #For each Idea form.instance.project = project if form.instance.sentence: sentence = form.instance.sentence validate_noun = [word for word in sentence.lower().split() if word in nouns] validate_verbs = [word for word in sentence.lower().split() if word in verbs] if (len(validate_noun) < 1): error = True messages.error(self.request, u'No noun was inserted into the sentence.', 'danger') if (len(validate_verbs) < 1): error = True messages.error(self.request, u'No verb was inserted into the sentence.', 'danger') if not error: formset.save() messages.success(self.request, u'Success!') return HttpResponseRedirect( project.get_absolute_url() ) else: return self.render_to_response(self.get_context_data(form=form))
cloud.html
Lorenzo Peña.. 28
作为一般规则,模型验证应该进入模型字段验证器或模型的clean
方法.表格验证应该采用表格clean
或clean_
方法.
如果你需要验证视图中的内容form_valid
,你可以使用form.add_error
然后,而不是重定向(或返回super(cloud, self).form_valid(form)
,无论如何重定向),你可以返回super(cloud, self).form_invalid(form)
.
检查:https: //docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.add_error
作为一般规则,模型验证应该进入模型字段验证器或模型的clean
方法.表格验证应该采用表格clean
或clean_
方法.
如果你需要验证视图中的内容form_valid
,你可以使用form.add_error
然后,而不是重定向(或返回super(cloud, self).form_valid(form)
,无论如何重定向),你可以返回super(cloud, self).form_invalid(form)
.
检查:https: //docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.add_error