FormView - Class Based Views Django
A FormView is a built-in class-based view used to display and handle forms in Django. Unlike CreateView or UpdateView, FormView does not tie directly to a model by default, making it useful for forms like contact forms, search forms, or any custom form not directly creating a database record.
When using class-based FormView:
- Specify the form class that will be used.
- Provide a template to render the form.
- Define a success URL to redirect after the form is successfully submitted.
- Optionally, override the form_valid method to handle form data.
Example: Consider a project named Core having an app named books.
Step 1: In core/URLs, set the path for the app.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('books.urls', namespace='books')),
]
Step 2: In core/settings.py, add the app name 'books' to the INSTALLED_APPS list
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books',
]
Step 3: In books/admin.py
from django.contrib import admin
from . import models
@admin.register(models.Books)
class AuthorAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
Step 4: Create a model in books/models.py
from django.db import models
from django.template.defaultfilters import slugify
class Books(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(null=True)
genre = models.CharField(max_length=100)
author = models.CharField(max_length=100)
isbn = models.IntegerField()
count = models.IntegerField(null=True, default=0)
Step 5: In books/forms.py, define a form for the model to use in a CreateView
from .models import Books
class AddForm(forms.ModelForm):
class Meta:
model = Books
fields = ('title', 'genre', 'author', 'isbn')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'genre': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.TextInput(attrs={'class': 'form-control'}),
'isbn': forms.TextInput(attrs={'class': 'form-control'}),
}
Step 6: After creating the form, create "CreateView" in geeks/views.py
from django.views.generic.edit import CreateView
from .forms import AddForm
class AddBookView(CreateView):
# model = Books
form_class = AddForm
template_name = 'add.html'
success_url = '/books/'
Step 7: Map URL to this view in books/urls.py
from django.urls import path
from .views import AddBookView
app_name = 'books'
urlpatterns = [
path('', AddBookView.as_view(), name='add'),
]
Step 8: Set Urls for books/urls.py
from django.urls import path
from .views import AddBookView
app_name = 'books'
urlpatterns = [
path('', AddBookView.as_view(), name='add'),
]
Step 9: Create a template for this view in books/add.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container" style="max-width:600px">
<div class="px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
<h1 class="display-4">Welcome to GFG Class Based Views Django</h1>
</div>
<div class="py-5">
<div class="row">
<div class="col-12">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Step 10: Run the app
python manage.py runserver
Visit: http://127.0.0.1:8000/
What is the main purpose of a FormView in Django?
-
A
To display a list of database records
-
B
To display and handle a form not directly tied to a model
-
C
To automatically create a database record for a model
-
D
To delete a record from database
FormView renders a form, validates submitted data, and processes it — often used for contact forms or search forms rather than model-based creation.
Which attributes must be specified when using FormView?
-
A
model and fields
-
B
database engine and MEDIA_ROOT
-
C
static URL and media URL
-
D
form_class, template_name, and success_url
FormView requires a form class for form definition, a template to render the form, and a URL to redirect upon successful form submission.
What method can be overridden in FormView to handle custom processing once form data is valid?
-
A
form_valid
-
B
get_object
-
C
save_form
-
D
clean_data
Overriding form_valid lets custom code run on submitted valid data before redirecting to success_url.