在FormView form_valid方法中更新上下文数据? [英] Updating context data in FormView form_valid method?
问题描述
我有一个类 QuestionView
,它来源于 FormView
类。这里
是一个代码片段来解释我的问题:
I have a class QuestionView
which is derived from the FormView
class. Here
is a code snippet to explain my problem:
class QuestionView(FormView):
...
context_var1 = y
def form_valid (self, form):
...
self.context_var1 = x
...
def get_context_data(self, **kwargs):
...
context['context_var1'] = self.context_var1
...
return context
如上所示,我在 form_valid
和$ b $中更新一组上下文变量b我打算在模板中使用这些更新的值 - 因此在上下文
字典中的变量。此代码的问题是,
context_var1
中的更改未被看到 - 可能是因为 get_context_data
在$ code> form_valid 方法之前调用
。是否有一个解决方案
这个?
As shown above, I update a set of context variables in form_valid
and
I intend to use the updated values of these in the template - hence the variables in the context
dictionary. The problem with this code is that the change in
context_var1
isn't seen - might be because get_context_data
is
called before the form_valid
method. Is there is a workaround for
this?
推荐答案
我这样做与 form_invalid
。以下是我如何做:
I do this with form_invalid
. Here's how I do it:
from django.views.generic import FormView
class ContextFormView(FormView):
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(**kwargs)
context['form'] = form
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form, **kwargs)
def form_invalid(self, form, **kwargs):
context = self.get_context_data(**kwargs)
context['form'] = form
return self.render_to_response(context)
你可以做同样的但是form_valid。通常,form_valid的正文如下所示:
You could do the same but for form_valid. Normally the body of form_valid looks like this:
def form_valid(self, form):
return HttpResponseRedirect(self.get_success_url())
你必须覆盖 post
和 form_valid
,因为发布
调用 form_valid
。
You would have to override both post
and form_valid
, because post
calls form_valid
.
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form, **kwargs)
else:
return self.form_invalid(form, **kwargs)
def form_valid(self, form, **kwargs):
# take some other action here
return HttpResponseRedirect(self.get_success_url())
哦,只是为了澄清,这个问题存在的原因是 ProcessFormView
类的 get
方法已损坏。它通常如下所示:
oh and just to clarify, the reason this problem exists is that the ProcessFormView
class's get
method is broken. It normally looks like this:
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
它只是把kwargs抛出去,(._。)
It just throws the kwargs away (._.)
这篇关于在FormView form_valid方法中更新上下文数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!