如果在基于类的视图中使用成功URL重定向到另一个页面失败,则条件满足重定向到一个页面

时间:2018-04-30 06:11:37

标签: django django-forms django-views

当if条件有效时,我想将页面重定向到success.html页面,如果无效则重定向到faild.html页面。如何使用基于类的视图。

class LogView(FormView):
    form_class = LogForm
    template_name = 'log.html'
    success_url='failed'
    def get_success_url(self):
        if not self.success_url:
                raise ImproperlyConfigured("No URL to redirect 
                to.Provide a success_url.")
        return str(self.success_url) 

    def form_valid(self,form):
            cc=''
            nam1 = self.request.POST.get('nam')
            roll1 = self.request.POST.get('roll')
            obj=Register.objects.all()
            for i in obj:
                if  str(i.name) == str(nam1) and  str(i.rollno) == str(roll1):




                else:
                    pass
            else:
                pass

2 个答案:

答案 0 :(得分:1)

您可以使用form_validform_invalid方法:

class LogView(FormView):
    form_class = LogForm
    template_name = 'log.html'
    success_url='failed'

    def form_valid(self, form):
        """
        If the form is valid, redirect to the supplied URL.
        """
        nam1 = self.request.POST.get('nam')
        roll1 = self.request.POST.get('roll')
        obj=Register.objects.filter(name=nam1, rollno=roll1).exists()
        if  obj:
            return HttpResponseRedirect(self.get_success_url())
        else:
            return HttpResponseRedirect('failed')   

    def form_invalid(self, form):
        """
        If the form is invalid
        """
        return HttpResponseRedirect('some_invalid_url')

答案 1 :(得分:0)

 class LogView(FormView):
    form_class = LogForm
    template_name = 'log.html'
    success_url='success'
    def form_valid(self, form):
        nam1 = self.request.POST.get('nam')
        roll1 = self.request.POST.get('roll')
        obj=Register.objects.filter(name=nam1, rollno=roll1).exists()
        if (obj==True):
            return HttpResponseRedirect(self.get_success_url())
        else:
            return HttpResponseRedirect('failed')