将基于函数的视图转换为基于类的视图



我试图通过POST方法在变量中获取表单数据,然后尝试验证它。我已经完成了它与django函数基于视图。但现在我想把它转换成django基于类的vied。所以谁能帮我把下面的代码转换成django基于类的视图呢?

from .forms import contact_form
def contact_us(request):
if request.method == "POST":
form = contact_form(request.POST)
# return HttpResponse(form)
if form.is_valid():
return HttpResponse("Data is valid")
else:
return HttpResponse("Data is invalid")

我的想法基本如下:"

from django.views.generic.edit import FormView
from .forms import ContactForm
class ContactUsView(FormView):
def post(self , request):
# this method will handle event when reques is come through POST method
def get(delf , request):
# this method will handle event when reques is come through POST method

"

您可以使用FormView[Django-doc]<一口>:

from django.views.generic.edit importFormView
from .forms import contact_form
class ContactUsView(FormView):
form_class = contact_form
template_name = 'name-of-template.html'
def form_valid(self, form):
return HttpResponse('Data is valid')
def form_invalid(self, form):
return HttpResponse('Data is invalid')

对于GET请求,默认的行为是将template_name作为form变量呈现为指定form_class的表单对象。


注意: Django中的表单是用PascalCase写的,而不是snake_case。所以你可能想把模型从contact_form重命名为ContactForm

相关内容

  • 没有找到相关文章

最新更新