更新 FormView form_valid 方法中的上下文数据?

发布于 2024-11-27 13:22:57 字数 629 浏览 0 评论 0原文

我有一个类 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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

却一份温柔 2024-12-04 13:22:57

我使用 form_invalid 来执行此操作。我是这样做的:

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 的正文如下所示:

def form_valid(self, form):
    return HttpResponseRedirect(self.get_success_url())

您必须重写 postform_valid,因为 post 调用 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 方法被破坏了。它通常看起来像这样:

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 扔掉 (._.)

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)

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())

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())

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))

It just throws the kwargs away (._.)

眉目亦如画i 2024-12-04 13:22:57

在views.py中

class UploadTest(FormView):
    template_name = 'test.html'
    ....
    plus_context = dict()

    def form_valid(self, form):
        ...
        self.plus_context['you_want_context'] = value
        ...
        return super(UploadTest, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(UploadTest, self).get_context_data(**kwargs)
        context['plus_context_key'] = self.plus_context
        return context

在test.html

<html>
    ....
    <body>
    ....
    // first post can not get plus_context_key
    {% if plus_context_key %}
        {{ plus_context_key.you_want_context }}
    {% endif %}    
    </body>
</html>

中我只是在Django 1.10.3中弄清楚了这种方式。
希望能帮到你

In views.py

class UploadTest(FormView):
    template_name = 'test.html'
    ....
    plus_context = dict()

    def form_valid(self, form):
        ...
        self.plus_context['you_want_context'] = value
        ...
        return super(UploadTest, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(UploadTest, self).get_context_data(**kwargs)
        context['plus_context_key'] = self.plus_context
        return context

In test.html

<html>
    ....
    <body>
    ....
    // first post can not get plus_context_key
    {% if plus_context_key %}
        {{ plus_context_key.you_want_context }}
    {% endif %}    
    </body>
</html>

I just figure out this way in Django 1.10.3.
Hope can help you

亢潮 2024-12-04 13:22:57

在 Django 2.0.1 中,您可以通过重写 get_context_dataform_invalid 来插入上下文数据。

在您的情况下,您可以执行以下覆盖之一:

class QuestionView(FormView):
    ...

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(
            self.get_context_data(
                form=form, 
                context_key=some_value
            )
        )

或者:

class QuestionView(FormView):
    ...

    def get_context_data(self, **kwargs):
        if 'context_key' not in kwargs:  # set value if not present
            kwargs['context_key'] = some_value
        return super().get_context_data(**kwargs)

Django 2.0.1 在后台将表单插入 get_context_data 的 kwargs 中。

# File: django.views.generic.edit

class FormMixin(ContextMixin):
    ...

    def form_valid(self, form):
        """If the form is valid, redirect to the supplied URL."""
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        """Insert the form into the context dict."""
        if 'form' not in kwargs:
            kwargs['form'] = self.get_form()
        return super().get_context_data(**kwargs)

In Django 2.0.1 you can insert context data by overriding either get_context_data or form_invalid.

In your case you could do one of the following overrides:

class QuestionView(FormView):
    ...

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(
            self.get_context_data(
                form=form, 
                context_key=some_value
            )
        )

Or:

class QuestionView(FormView):
    ...

    def get_context_data(self, **kwargs):
        if 'context_key' not in kwargs:  # set value if not present
            kwargs['context_key'] = some_value
        return super().get_context_data(**kwargs)

Django 2.0.1 inserts under the hood the form into the kwargs of get_context_data.

# File: django.views.generic.edit

class FormMixin(ContextMixin):
    ...

    def form_valid(self, form):
        """If the form is valid, redirect to the supplied URL."""
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        """Insert the form into the context dict."""
        if 'form' not in kwargs:
            kwargs['form'] = self.get_form()
        return super().get_context_data(**kwargs)
×纯※雪 2024-12-04 13:22:57

也许你可以使用这种方法:

class SomeView(View):

    def post(self, request):
        my_form = MyForm(request.POST)
        if my_form.is_valid():
            context['foo'] = 'bar'

        return render(request, 'valid/path.html', context)

Maybe you can use this approach:

class SomeView(View):

    def post(self, request):
        my_form = MyForm(request.POST)
        if my_form.is_valid():
            context['foo'] = 'bar'

        return render(request, 'valid/path.html', context)
久光 2024-12-04 13:22:57

如果保存成功,则传递 plus_context:

class SomeUpdateView(UpdateView):
    ...
    success_url = reverse_lazy('SomeUpdateView')
    plus_context = dict()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.plus_context:
            context['success'] = self.plus_context['pass_to_view_just_after_save_successful']
        return context

    def form_valid(self, form, **kwargs):
        self.object.save()
        self.plus_context['pass_to_view_just_after_save_successful'] = 'Save successful!'
        return super(SomeUpdateView, self).form_valid(form)

在模板中,如下所示:

{% if success %}
<p>{{ success }}</p>
{% endif %}

Pass plus_context just if save successfull:

class SomeUpdateView(UpdateView):
    ...
    success_url = reverse_lazy('SomeUpdateView')
    plus_context = dict()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.plus_context:
            context['success'] = self.plus_context['pass_to_view_just_after_save_successful']
        return context

    def form_valid(self, form, **kwargs):
        self.object.save()
        self.plus_context['pass_to_view_just_after_save_successful'] = 'Save successful!'
        return super(SomeUpdateView, self).form_valid(form)

in template something like:

{% if success %}
<p>{{ success }}</p>
{% endif %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文