更新 FormView form_valid 方法中的上下文数据?
我有一个类 QuestionView
,它派生自 FormView
类。这里 是解释我的问题的代码片段:
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
中的一组上下文变量,并且 我打算在模板中使用这些的更新值 - 因此使用 context
字典中的变量。这段代码的问题在于, 未看到 context_var1
- 可能是因为 get_context_data
是 在 form_valid
方法之前调用。有没有解决方法 这?
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
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 incontext_var1
isn't seen - might be because get_context_data
is
called before the form_valid
method. Is there is a workaround for
this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我使用
form_invalid
来执行此操作。我是这样做的:你可以做同样的事情,但对于 form_valid 。通常 form_valid 的正文如下所示:
您必须重写
post
和form_valid
,因为post
调用form_valid
>。哦,澄清一下,这个问题存在的原因是 ProcessFormView 类的 get 方法被破坏了。它通常看起来像这样:
它只是将 kwargs 扔掉
(._.)
I do this with
form_invalid
. Here's how I do it:You could do the same but for form_valid. Normally the body of form_valid looks like this:
You would have to override both
post
andform_valid
, becausepost
callsform_valid
.oh and just to clarify, the reason this problem exists is that the
ProcessFormView
class'sget
method is broken. It normally looks like this:It just throws the kwargs away
(._.)
在views.py中
在test.html
中我只是在Django 1.10.3中弄清楚了这种方式。
希望能帮到你
In views.py
In test.html
I just figure out this way in Django 1.10.3.
Hope can help you
在 Django 2.0.1 中,您可以通过重写
get_context_data
或form_invalid
来插入上下文数据。在您的情况下,您可以执行以下覆盖之一:
或者:
Django 2.0.1 在后台将表单插入
get_context_data
的 kwargs 中。In Django 2.0.1 you can insert context data by overriding either
get_context_data
orform_invalid
.In your case you could do one of the following overrides:
Or:
Django 2.0.1 inserts under the hood the form into the kwargs of
get_context_data
.也许你可以使用这种方法:
Maybe you can use this approach:
如果保存成功,则传递 plus_context:
在模板中,如下所示:
Pass plus_context just if save successfull:
in template something like: