当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
答案 0 :(得分:1)
您可以使用form_valid
和form_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')