【问题标题】:Django Success_urlDjango Success_url
【发布时间】:2014-02-01 16:06:57
【问题描述】:

我构建了一个包含两个字段的 FormView。我想使用表单将查询传递给视图。

class SectorForm(forms.Form):
    date = forms.DateField()
    days = forms.IntegerField(max_value=365, min_value=1)

有没有办法可以让我的 FormView 并从有效的表单字段构建 success_url

所以覆盖 get_success_url。

      def get_success_url(self): 
        return reverse_lazy('queryable-view' date days)

我以为我可以从 form_valid 中取出它,但从未成功。

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    get_success_url 无权访问 Form 实例,但 form_valid 可以。试试这样的:

    from django.shortcuts import redirect
    
    class YourFormView(FormView):
        # ...
    
        def form_valid(self, form):
            date, days = form.cleaned_data['date'], form.cleaned_data['days']
            return redirect('queryable-view', date, days)
    

    【讨论】:

    • 谢谢!!那行得通。我最终使用了return HttpResponseRedirect(reverse('queryable-view', args=(date.strftime("%Y%m%d"), days)))
    【解决方案2】:

    我曾经遇到过类似的问题。当您使用表单时,您可能不会使用 kwargs 并且 get_success_url 无法访问表单(如前所述) 我已经解决了:

    class YourView(CreateView):
    appointment_id =0
    
    def form_valid(self,form):
        appointment = form.save()
        self.appointment_id = appointment.pk
        print self.appointment_id
    
        return super(AppointmentCreate,self).form_valid(form)
    
    def get_success_url(self, **kwargs):         
        if  kwargs != None:
            return reverse_lazy('payment', kwargs = {'appid': self.appointment_id})
    

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 2023-03-20
      • 1970-01-01
      • 2017-06-23
      • 2011-11-15
      • 2018-12-09
      • 2013-12-05
      • 2017-04-14
      • 1970-01-01
      相关资源
      最近更新 更多