如何在FormView的get_success_url中从form_valid访问变量?

时间:2019-01-27 06:30:31

标签: django python-3.x

用户提交我的表单后,我想根据表单输入将用户重定向到两个URL之一。这是我的代码:

class MyClass(FormView):
    template_name = 'my_template.html'
    form_class = MyForm


    def form_valid(self, form, *args, **kwargs):
        response = super().form_valid(form, *args, **kwargs)
        self.title = form.cleaned_data.get('title')
        self.special_id = form.cleaned_data.get('special_id')
        return response

    def get_success_url(self):
        if self.special_id:
             next_page = reverse_lazy('home:home', kwargs={'special_id': self.special_id})
        else:
             initial_link = reverse_lazy('home:home')
             next_page = '{}?title={}'.format(initial_link, self.title)


        return next_page

上面的代码无效。一个问题是get_success_url无法识别变量self.special_idself.title。如何根据表单中的值将用户重定向到其他页面?

2 个答案:

答案 0 :(得分:0)

为什么不这样尝试?

class MyClass(FormView):
    template_name = 'my_template.html'
    form_class = MyForm


    def form_valid(self, form, *args, **kwargs):

        title = form.cleaned_data.get('title')
        special_id = form.cleaned_data.get('special_id')
        return HttpResponseRedirect(self.get_success_url(title, special_id))

    def get_success_url(self, title=None, special_id=None):
        if special_id:
             next_page = reverse_lazy('home:home', kwargs={'special_id': self.special_id})
        else:
             initial_link = reverse_lazy('home:home')
             next_page = '{}?title={}'.format(initial_link, title)

        return next_page

因为,当您呼叫super().form_valid(form, *args, **kwargs)时,它将呼叫return HttpResponseRedirect(self.get_success_url(title, special_id))。因此,您无需调用super就可以自己完成此操作。可以参考here

OR

您可以尝试这样:

def form_valid(self, form, *args, **kwargs):
    self.title = form.cleaned_data.get('title')
    self.special_id = form.cleaned_data.get('special_id')
    return super().form_valid(form, *args, **kwargs)  # call super at the end

def get_success_url(self):
    if self.special_id:
         next_page = reverse_lazy('home:home', kwargs={'special_id': self.special_id})
    else:
         initial_link = reverse_lazy('home:home')
         next_page = '{}?title={}'.format(initial_link, self.title)
    return next_page

答案 1 :(得分:0)

使用这样的实例变量:

class MyClass(FormView):
  template_name = 'my_template.html'
  form_class = MyForm

  def __init__(self):
    self.title = None
    self.special_id = None

  def form_valid(self, form):
    self.title = form.cleaned_data.get('title')
    self.special_id = form.cleaned_data.get('special_id')
    return super().form_valid(form) 
    # for python 2: return super(MyClass, self).form_valid(form) 
  def get_success_url(self):
    if self.special_id:
        next_page = reverse_lazy('home:home', kwargs={'special_id': self.special_id})
    else:
        response = 
        initial_link = reverse_lazy('home:home')
        next_page = '{}?title={}'.format(initial_link, self.title)

    return next_page