简体   繁体   中英

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. I have done it with django function based view. But now I want to convert it into django class based vied. So can any one help to convert my following code to django class based view.

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] :

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 .


Note : Forms in Django are written in PascalCase , not snake_case , so you might want to rename the model from contact_form to ContactForm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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