简体   繁体   English

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

[英]convert function based view to class based view django

I am tried to do get form data by POST method in a variable and then try to validate it.我试图通过变量中的 POST 方法获取表单数据,然后尝试验证它。 I have done it with django function based view.我已经使用基于 django 函数的视图完成了它。 But now I want to convert it into django class based vied.但现在我想将它转换为基于 django 类的 vied。 So can any one help to convert my following code to django class based view.因此,任何人都可以帮助将我的以下代码转换为基于 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")

my idea is basically like as below: '''我的想法基本上如下:'''

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

''' '''

You can use a FormView [Django-doc] :您可以使用FormView [Django-doc]

from django.views.generic.edit import FormView
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')

For a GET request, the default behavior will be to render the template_name with as form variable the form object of the specified form_class .对于 GET 请求,默认行为是使用指定form_class的表单对象作为form变量呈现template_name


Note : Forms in Django are written in PascalCase , not snake_case , so you might want to rename the model from contact_form to ContactForm .注意:Django 中的表单是用PascalCase编写的,而不是snake_case ,因此您可能希望将模型从contact_form重命名为ContactForm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM