Unit 4: Forms in Django - Practice Quiz
1 What is the main purpose of an HTML form in a Django application?
2 Which HTML element is used to create a form?
<table>
<section>
<script>
<form>
3 Which form control is commonly used to submit an HTML form?
4 Where is form data normally placed when the GET method is used?
5 Which HTTP method is commonly used when a form changes data on the server?
6 Which Django request attribute identifies the HTTP method used?
request.session
request.user
request.method
request.path
7 Which Django object contains form values submitted using POST?
request.META
request.POST
request.GET
request.FILES
8 Which Django class is commonly extended to create a standard form?
forms.Template
forms.View
forms.Model
forms.Form
9 How are fields usually declared in a Django form class?
10 Which Django form field is suitable for a short line of text?
forms.DateField
forms.CharField
forms.BooleanField
forms.FileField
11
What is the main purpose of Django's ModelForm?
12 Which template expression renders a Django form with fields wrapped in paragraph elements?
{{ form.as_div }}
{{ form.as_p }}
{{ form.as_table }}
{{ form.as_ul }}
13 What does CSRF stand for?
14 What is the goal of a CSRF attack?
15 Which template tag adds CSRF protection to a Django POST form?
{% csrf_check %}
{% request_token %}
{% secure_form %}
{% csrf_token %}
16
Where should {% csrf_token %} normally be placed?
17 What response is commonly returned when Django rejects a request because of a missing or invalid CSRF token?
18 Why is a redirect commonly performed after successfully processing a POST request?
19 Which Django shortcut is commonly used to send the user to another URL after processing a form?
reverse_lazy()
render()
include()
redirect()
20 Which method checks whether submitted data in a Django form is valid?
form.submit()
form.render()
form.is_valid()
form.save()
21 A product filter form allows users to choose a category and minimum price without changing server data. Which form method is most appropriate?
GET because the filter represents a read-only query
PUT because the filter updates the displayed products
DELETE because old filter values must be removed
POST because every HTML form should submit privately
22
An HTML form contains <input name="email">, but its submitted value does not appear in the request data. Which issue is the most likely cause?
name attribute
<form> element
23
A Django search view receives a request for /search/?q=django&page=2. How should the view retrieve the search term?
request.FILES.get("q")
request.COOKIES.get("q")
request.POST.get("q")
request.GET.get("q")
24
A view should create a comment only when a form is submitted using POST. Which condition correctly checks the HTTP method?
if request.POST == "POST":
if request.method == request.POST:
if request.GET.get("POST"):
if request.method == "POST":
25
A form submits multiple checkboxes with the same name, skills. Which expression retrieves all selected values?
request.POST.get("skills")
request.POST.values("skills")
request.POST.getlist("skills")
request.POST.items("skills")
26
A view must display an empty ContactForm for GET requests and a bound form for POST requests. Which initialization handles both cases correctly?
form = ContactForm(request.method or None)
form = ContactForm(request.GET or request.POST)
form = ContactForm(request.POST.is_valid())
form = ContactForm(request.POST or None)
27
A ModelForm should allow users to edit only a book's title and publication_date. Which Meta configuration is appropriate?
form = Book and exclude = ["title", "publication_date"]
form = Book and include = ["title", "publication_date"]
model = Book and widgets = ["title", "publication_date"]
model = Book and fields = ["title", "publication_date"]
28
A template renders {{ form.as_p }} inside a <form> element, but clicking Submit sends no request. What must still be added?
<form> element around the submit action
<button type="submit">Save</button>
29
A Django form includes a FileField, but uploaded files are always missing during validation. Which combination is required?
enctype="multipart/form-data" and ContactForm(request.POST, request.FILES)
accept="multipart/form-data" and ContactForm(request.POST)
method="GET" and ContactForm(request.GET, request.COOKIES)
enctype="text/plain" and ContactForm(request.FILES, request.GET)
30 A malicious page causes a logged-in user's browser to submit a hidden form to a banking site. Why might the forged request be authenticated?
GET
31 Which application behavior creates the clearest CSRF risk?
GET request
32
Why does changing a state-modifying endpoint from GET to POST not, by itself, prevent CSRF?
POST request never includes session cookies unless JavaScript adds them
POST requests as trusted GET requests
POST
POST requests from static file requests
33
A Django template posts to an internal view and receives 403 CSRF verification failed. The middleware is enabled. What is the usual template fix?
CSRF_COOKIE_SECURE=False to every form action
{% csrf_token %} inside the submitted <form>
{{ request.user }} inside the submitted <form>
csrf=True to the form's method attribute
34
JavaScript sends an AJAX POST request to a Django view protected by CSRF middleware. Where is the token commonly supplied?
User-Agent request header
Content-Length response header
X-CSRFToken request header
Accept-Language response header
35
A developer adds @csrf_exempt to a cookie-authenticated profile update view to fix a 403 response. What is the best assessment?
36 After successfully saving a form, a Django view renders the success template directly. Refreshing the page resubmits the form. Which change implements Post/Redirect/Get?
200 response
redirect("success") after saving valid data
redirect("success") before checking form validity
render(request, "success.html") after saving data
37
A valid ModelForm creates a new article. The success page needs the article's generated primary key. Which approach is appropriate?
article = form.cleaned_data followed by render("article-detail", article.pk)
article = form.is_valid() followed by redirect("article-detail", pk=article.pk)
article = form.save() followed by redirect("article-detail", pk=article.pk)
article = request.POST followed by redirect("article-detail", pk=article.id)
38
A form has a field named age, and only that field needs a custom rule requiring users to be at least 18. Which method should the form define?
validate_age(self)
is_valid_age(self)
cleaned_age(self)
clean_age(self)
39
A registration form must reject data when password and confirm_password differ. Where should this cross-field validation normally be implemented?
password widget's attributes
{% csrf_token %} tag
clean() method
form.save()
40
A view accesses form.cleaned_data["email"] immediately after constructing ContactForm(request.POST). What should it do first?
form.has_changed() so Django accepts all submitted values
form.as_p() so Django converts the field into cleaned data
form.is_valid() and access the value only when validation succeeds
form.save() and then inspect the original submitted dictionary
41
A Django view uses GET /orders/42/cancel/ to cancel an order and then returns a confirmation page. Even if authentication and CSRF checks are added, what is the most fundamental design problem?
42
A request URL is /search/?tag=django&tag=python. Which expression reliably retrieves both submitted values from Django's request.GET?
request.GET['tag']
list(request.GET.get('tag'))
request.GET.get('tag')
request.GET.getlist('tag')
43
A search view creates its form with SearchForm(request.GET or None). What subtle behavior occurs when the page is requested as /search/ with no query parameters?
QueryDict and immediately validates
QueryDict is replaced by None
ValidationError because no search fields were supplied
request.POST because request.GET evaluates to false
44
A form is instantiated as ProfileForm(data={'name': ''}, initial={'name': 'Ada'}), and name is required. What happens when is_valid() is called?
initial
initial replaces the empty submitted value
45
For a field named age, which sequence best describes Django's normal validation flow when no earlier stage raises an error?
to_python() → validate() → validators → clean_age() → Form.clean()
Form.clean() → clean_age() → Field.clean() → validators
to_python() → Form.clean() → clean_age()
clean_age() → to_python() → validators → Form.clean()
46
A form must reject a date range when end_date < start_date, while keeping the error associated with the combination rather than either field alone. What is the most appropriate implementation?
Http404 from Form.is_valid() after comparing both raw values
ValidationError from the view after calling form.save()
ValidationError from Form.clean() after reading both cleaned values
ValidationError from clean_start_date() before reading end_date
47
Inside Form.clean(), code executes self.add_error('email', 'Domain is blocked') after email was initially cleaned successfully. What important side effect does Django apply?
email to its initial value
email from cleaned_data
48
A ModelForm overrides clean() but does not call super().clean(). Individual fields still validate. Which behavior is especially at risk?
49
A valid ModelForm contains a many-to-many field. The view calls instance = form.save(commit=False), modifies the instance, and then calls instance.save(). What must generally happen next?
form.is_valid() again after the instance has been saved
instance.full_clean() before saving any scalar fields
instance.refresh_from_db() before assigning relationships
form.save_m2m() after the instance has a primary key
50
A form has document = forms.FileField(). The browser submits a valid multipart request, but the view constructs UploadForm(request.POST) and validation reports that the file is missing. What correction is required?
UploadForm(request.body, request.POST)
UploadForm(request.POST, request.FILES)
UploadForm(request.FILES, request.GET)
UploadForm(files=request.POST)
51 Why can an attacker often launch a CSRF attack without learning the victim's session cookie?
52 Django may render a masked CSRF token whose value changes between responses even though the underlying CSRF secret remains valid. What is the primary purpose of this masking?
53
A same-origin JavaScript client sends JSON with fetch() to a CSRF-protected Django POST endpoint. There is no HTML form body. Which approach integrates with Django's standard CSRF middleware?
Access-Control-Allow-Origin in the request headers
Authorization header
X-CSRFToken header
54
A page performs only JavaScript-based POST requests and renders no {% csrf_token %}. Consequently, some first-time visitors receive no CSRF cookie. Which Django tool directly addresses this?
require_http_methods
SECURE_HSTS_INCLUDE_SUBDOMAINS
ensure_csrf_cookie
csrf_exempt
55
After moving a Django form to https://app.example.com, legitimate POST requests originating from https://forms.example.net fail CSRF origin checks despite carrying a valid token. What configuration is relevant?
forms.example.net to ALLOWED_HOSTS only
https://forms.example.net to CSRF_TRUSTED_ORIGINS
app.example.com to CSRF_COOKIE_PATH
https://app.example.com to CORS_ALLOW_HEADERS
56
A successful POST creates a payment record and directly renders success.html. Refreshing the page can resubmit the POST. Which change correctly applies the Post/Redirect/Get pattern?
HttpResponse(status=200) with a Location response header
redirect('payment-success') after the record is committed
57 A view redirects after both valid and invalid POST submissions. On invalid input, the redirected page displays an unbound form and loses all field errors. What is the best default design?
58 A purchase view follows PRG, but two nearly simultaneous POST requests with the same payload still create duplicate purchases. What does this demonstrate?
59
A page displays two instances of the same AddressForm, but both forms use identical field names such as city. How should the forms be constructed so each binds only its own submitted fields?
auto_id pattern when validating
initial dictionary when rendering
label_suffix when binding
prefix when rendering and binding
60
A form defines account_id = forms.IntegerField(disabled=True, initial=17). A malicious client submits account_id=999. Assuming the form is otherwise valid, which value appears in cleaned_data['account_id']?
None, because disabled fields are excluded from cleaned_data
17, because a disabled Django field uses its initial value
999, because POST data always overrides field configuration
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →