一尘不染

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

django

我有一个QuestionViewFormView该类派生的类。这是一个代码片段来解释我的问题:

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方法之前被调用。有没有解决方法?


阅读 488

收藏
2020-04-01

共1个答案

一尘不染

我这样做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))

它只是把垃圾扔掉了 (._.)

2020-04-01