Reputation: 21
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
'''
Upvotes: 1
Views: 141
Reputation: 477853
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
tocontact_form
ContactForm
.
Upvotes: 1