Django CBV: form processing
Keywords:
Django
less
Database
CBV
Reference link:
- https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-editing/ (official document of Django)
CBV is Class Based View, which is to build a view through class. Different from FBV(Function Based View), by using class inheritance and mixins, CBV has higher code reusability and less code to be implemented by itself
Form validation is required when users submit data and before data is stored in the database. Here is how form and CBV work together
Basic Forms
from myapp.forms import ContactForm
from django.views.generic.edit import FormView
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/'
- Define some properties of ContactView:
- template_name is the rendered form template
- form_class is the form class, which defines the fields and types of the form.
- success_url is the url to jump after the form is verified successfully. Here is a hard coded url. You can also use the reverse function to pass in the name of the url to match the corresponding url
- Can customize form_valid() method, redirect to success after the form is verified successfully_ Before the URL, do some additional operations:
def form_valid(self, form):
return super().form_valid(form)
- Form of parent class_ All you do in the valid () method is redirect to the property success_ The route corresponding to the URL
Model Forms
- ModelForm is often used with CreateView and UpdateView, which are closely related to Model
- Take CreateView for example, its form_ After the form is validated successfully, the valid method creates a record to store the data in the form
- In addition to the fields entered from the form, there are usually other data that need to be saved (such as the creator of this record, creation time, etc.), or some other operations. You can rewrite the form_ The valid () method, such as the following view to create a blog:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from myapp.models import Post
class CreatePostView(LoginRequiredMixin, CreateView):
model = Post
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
- In the above code, LoginRequiredMixin specifies that execution can only be continued if the user is logged in. If there is no login, it will be redirected to login_url
- In form_ In the valid method, set the author field to the current login user, and then continue to execute the method of the parent class.
Using AJAX
- If the form submission in the template is completed through Ajax request, rather than POST form submission, you can customize a mixin, add Ajax support, and use request.is_ajax() can determine whether the current request is an Ajax request or not:
from django.http import JsonResponse
from django.views.generic.edit import CreateView
from myapp.models import Author
class AjaxableResponseMixin:
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super().form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
response = super().form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return JsonResponse(data)
else:
return response
class AuthorCreate(AjaxableResponseMixin, CreateView):
model = Author
fields = ['name']
- In the above code:
- Ajax ableresponsemixin must be associated with Model based view classes (CreateView, UpdateView, DeleteView )Use together
- adopt self.request.is_ajax() to determine the type of return
Posted by miha on Mon, 15 Jun 2020 00:51:15 -0700