Unit 4: Forms in Django - Practice Quiz

INT253 — Web Development In Python Using Django 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of an HTML form in a Django application?

Introduction to Forms Easy
A. To collect input from users
B. To create database backups
C. To configure the web server
D. To install Python packages

2 Which HTML element is used to create a form?

Introduction to Forms Easy
A. <table>
B. <section>
C. <script>
D. <form>

3 Which form control is commonly used to submit an HTML form?

Introduction to Forms Easy
A. A heading
B. A paragraph
C. A button
D. A label

4 Where is form data normally placed when the GET method is used?

Using GET, POST and HTTP Easy
A. In the URL query string
B. In the server log only
C. In a database table
D. In a CSS stylesheet

5 Which HTTP method is commonly used when a form changes data on the server?

Using GET, POST and HTTP Easy
A. TRACE
B. GET
C. POST
D. HEAD

6 Which Django request attribute identifies the HTTP method used?

Using GET, POST and HTTP Easy
A. request.session
B. request.user
C. request.method
D. request.path

7 Which Django object contains form values submitted using POST?

Using GET, POST and HTTP Easy
A. request.META
B. request.POST
C. request.GET
D. request.FILES

8 Which Django class is commonly extended to create a standard form?

Building forms using Django Easy
A. forms.Template
B. forms.View
C. forms.Model
D. forms.Form

9 How are fields usually declared in a Django form class?

Building forms using Django Easy
A. As template blocks
B. As class attributes
C. As database queries
D. As URL patterns

10 Which Django form field is suitable for a short line of text?

Building forms using Django Easy
A. forms.DateField
B. forms.CharField
C. forms.BooleanField
D. forms.FileField

11 What is the main purpose of Django's ModelForm?

Building forms using Django Easy
A. To generate models from templates
B. To generate URLs from views
C. To generate forms from models
D. To generate settings from middleware

12 Which template expression renders a Django form with fields wrapped in paragraph elements?

Building forms using Django Easy
A. {{ form.as_div }}
B. {{ form.as_p }}
C. {{ form.as_table }}
D. {{ form.as_ul }}

13 What does CSRF stand for?

Introduction to Cross Site Request Forgery (CSRF) Easy
A. Central Server Response Function
B. Cross-Site Request Forgery
C. Cross-System Routing Framework
D. Client-Side Request Format

14 What is the goal of a CSRF attack?

Introduction to Cross Site Request Forgery (CSRF) Easy
A. To force an unwanted user action
B. To style pages without CSS
C. To speed up database queries
D. To resize images in a browser

15 Which template tag adds CSRF protection to a Django POST form?

CSRF support in Django Easy
A. {% csrf_check %}
B. {% request_token %}
C. {% secure_form %}
D. {% csrf_token %}

16 Where should {% csrf_token %} normally be placed?

CSRF support in Django Easy
A. Inside the URL file
B. Inside the model class
C. Inside the settings file
D. Inside a POST form

17 What response is commonly returned when Django rejects a request because of a missing or invalid CSRF token?

CSRF support in Django Easy
A. 301 Moved Permanently
B. 404 Not Found
C. 403 Forbidden
D. 200 OK

18 Why is a redirect commonly performed after successfully processing a POST request?

Implementing POST redirect in Django Easy
A. To disable browser navigation
B. To remove all form validation
C. To convert POST into CSS
D. To prevent duplicate form submissions

19 Which Django shortcut is commonly used to send the user to another URL after processing a form?

Implementing POST redirect in Django Easy
A. reverse_lazy()
B. render()
C. include()
D. redirect()

20 Which method checks whether submitted data in a Django form is valid?

Data validation with Django forms Easy
A. form.submit()
B. form.render()
C. form.is_valid()
D. 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?

Introduction to Forms Medium
A. Use GET because the filter represents a read-only query
B. Use PUT because the filter updates the displayed products
C. Use DELETE because old filter values must be removed
D. Use 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?

Introduction to Forms Medium
A. The input uses a lowercase value for its name attribute
B. The input does not include a CSS class for form fields
C. The input is placed outside the submitted <form> element
D. The input does not include a JavaScript event listener

23 A Django search view receives a request for /search/?q=django&page=2. How should the view retrieve the search term?

Using GET, POST and HTTP Medium
A. request.FILES.get("q")
B. request.COOKIES.get("q")
C. request.POST.get("q")
D. 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?

Using GET, POST and HTTP Medium
A. if request.POST == "POST":
B. if request.method == request.POST:
C. if request.GET.get("POST"):
D. if request.method == "POST":

25 A form submits multiple checkboxes with the same name, skills. Which expression retrieves all selected values?

Using GET, POST and HTTP Medium
A. request.POST.get("skills")
B. request.POST.values("skills")
C. request.POST.getlist("skills")
D. 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?

Building forms using Django Medium
A. form = ContactForm(request.method or None)
B. form = ContactForm(request.GET or request.POST)
C. form = ContactForm(request.POST.is_valid())
D. 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?

Building forms using Django Medium
A. form = Book and exclude = ["title", "publication_date"]
B. form = Book and include = ["title", "publication_date"]
C. model = Book and widgets = ["title", "publication_date"]
D. 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?

Building forms using Django Medium
A. A script that serializes every field before submission
B. A second <form> element around the submit action
C. A hidden control containing the Python form class name
D. A submit control such as <button type="submit">Save</button>

29 A Django form includes a FileField, but uploaded files are always missing during validation. Which combination is required?

Building forms using Django Medium
A. enctype="multipart/form-data" and ContactForm(request.POST, request.FILES)
B. accept="multipart/form-data" and ContactForm(request.POST)
C. method="GET" and ContactForm(request.GET, request.COOKIES)
D. 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?

Introduction to Cross Site Request Forgery (CSRF) Medium
A. The browser converts the forged request into a trusted GET
B. The malicious page can directly read every banking database row
C. The browser may automatically include the banking site's cookies
D. The banking server automatically disables authentication for forms

31 Which application behavior creates the clearest CSRF risk?

Introduction to Cross Site Request Forgery (CSRF) Medium
A. Validating a local form field before enabling its submit button
B. Displaying a public article through an anonymous GET request
C. Serving a static stylesheet through a cached HTTP response
D. Changing an email address through a cookie-authenticated request

32 Why does changing a state-modifying endpoint from GET to POST not, by itself, prevent CSRF?

Introduction to Cross Site Request Forgery (CSRF) Medium
A. A POST request never includes session cookies unless JavaScript adds them
B. A browser always rewrites cross-site POST requests as trusted GET requests
C. An attacker can also cause a browser to submit a cross-site form using POST
D. A server cannot distinguish 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 support in Django Medium
A. Add CSRF_COOKIE_SECURE=False to every form action
B. Place {% csrf_token %} inside the submitted <form>
C. Place {{ request.user }} inside the submitted <form>
D. Add 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?

CSRF support in Django Medium
A. In the User-Agent request header
B. In the Content-Length response header
C. In the X-CSRFToken request header
D. In the 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?

CSRF support in Django Medium
A. It encrypts submitted fields before the middleware processes the request
B. It removes CSRF checking and exposes the update action to forged requests
C. It refreshes the CSRF token and protects the action from replay attacks
D. It limits the view to same-origin requests generated by Django templates

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?

Implementing POST redirect in Django Medium
A. Return the bound form with an HTTP 200 response
B. Return redirect("success") after saving valid data
C. Return redirect("success") before checking form validity
D. Return 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?

Implementing POST redirect in Django Medium
A. article = form.cleaned_data followed by render("article-detail", article.pk)
B. article = form.is_valid() followed by redirect("article-detail", pk=article.pk)
C. article = form.save() followed by redirect("article-detail", pk=article.pk)
D. 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?

Data validation with Django forms Medium
A. validate_age(self)
B. is_valid_age(self)
C. cleaned_age(self)
D. 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?

Data validation with Django forms Medium
A. In the password widget's attributes
B. In the template's {% csrf_token %} tag
C. In the form's clean() method
D. In the view after calling form.save()

40 A view accesses form.cleaned_data["email"] immediately after constructing ContactForm(request.POST). What should it do first?

Data validation with Django forms Medium
A. Call form.has_changed() so Django accepts all submitted values
B. Call form.as_p() so Django converts the field into cleaned data
C. Call form.is_valid() and access the value only when validation succeeds
D. Call 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?

Using GET, POST and HTTP Hard
A. GET responses cannot contain dynamically generated HTML
B. GET requests may be cached or prefetched despite being expected to be safe
C. GET responses cannot redirect to another URL after processing
D. GET requests cannot include path parameters such as an order ID

42 A request URL is /search/?tag=django&tag=python. Which expression reliably retrieves both submitted values from Django's request.GET?

Using GET, POST and HTTP Hard
A. request.GET['tag']
B. list(request.GET.get('tag'))
C. request.GET.get('tag')
D. 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?

Introduction to Forms Hard
A. The form is bound to an empty QueryDict and immediately validates
B. The form is unbound because the empty QueryDict is replaced by None
C. The form raises ValidationError because no search fields were supplied
D. The form uses 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?

Introduction to Forms Hard
A. The form is invalid because bound data takes precedence over initial
B. The form is unbound because the submitted name contains no characters
C. The form is valid because initial replaces the empty submitted value
D. The form is valid because empty strings are omitted from bound data

45 For a field named age, which sequence best describes Django's normal validation flow when no earlier stage raises an error?

Data validation with Django forms Hard
A. to_python()validate() → validators → clean_age()Form.clean()
B. Form.clean()clean_age()Field.clean() → validators
C. validators → to_python()Form.clean()clean_age()
D. 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?

Data validation with Django forms Hard
A. Raise Http404 from Form.is_valid() after comparing both raw values
B. Raise ValidationError from the view after calling form.save()
C. Raise ValidationError from Form.clean() after reading both cleaned values
D. Raise 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?

Data validation with Django forms Hard
A. It restores email to its initial value
B. It converts the error into a non-field error
C. It stops validation of every remaining field
D. It removes 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?

Data validation with Django forms Hard
A. The form may silently switch from bound to unbound state
B. Model uniqueness constraints may not be checked by the form
C. Required HTML attributes may disappear from rendered widgets
D. Submitted strings may no longer be converted to Python values

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?

Building forms using Django Hard
A. Call form.is_valid() again after the instance has been saved
B. Call instance.full_clean() before saving any scalar fields
C. Call instance.refresh_from_db() before assigning relationships
D. Call 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?

Building forms using Django Hard
A. Construct UploadForm(request.body, request.POST)
B. Construct UploadForm(request.POST, request.FILES)
C. Construct UploadForm(request.FILES, request.GET)
D. Construct UploadForm(files=request.POST)

51 Why can an attacker often launch a CSRF attack without learning the victim's session cookie?

Introduction to Cross Site Request Forgery (CSRF) Hard
A. The victim's browser automatically attaches matching cookies to the forged request
B. Django copies the victim's session cookie into every submitted HTML field
C. HTTP permits the attacker to read cookies belonging to every visited origin
D. The server accepts any session identifier supplied through the query string

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?

CSRF support in Django Hard
A. It allows one CSRF cookie to authenticate several unrelated domains
B. It encrypts all submitted form fields before network transmission
C. It reduces secret leakage through compression-based side channels
D. It prevents JavaScript from reading any token present in the DOM

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?

CSRF support in Django Hard
A. Set Access-Control-Allow-Origin in the request headers
B. Send the session ID in the Authorization header
C. Send the CSRF token in the X-CSRFToken header
D. Append the CSRF token only to the URL fragment

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?

CSRF support in Django Hard
A. Wrap the page view with require_http_methods
B. Enable SECURE_HSTS_INCLUDE_SUBDOMAINS
C. Decorate the page view with ensure_csrf_cookie
D. Decorate the POST endpoint with 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?

CSRF support in Django Hard
A. Add forms.example.net to ALLOWED_HOSTS only
B. Add https://forms.example.net to CSRF_TRUSTED_ORIGINS
C. Add app.example.com to CSRF_COOKIE_PATH
D. Add 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?

Implementing POST redirect in Django Hard
A. Render the same template with an empty form after the record is committed
B. Redirect to the POST endpoint before attempting to create the record
C. Return HttpResponse(status=200) with a Location response header
D. Return 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?

Implementing POST redirect in Django Hard
A. Store the complete form object permanently in the user's session
B. Render the bound form on invalid POST and redirect only after success
C. Return a success redirect while recording errors only in server logs
D. Redirect invalid POST data by placing every field in the query string

58 A purchase view follows PRG, but two nearly simultaneous POST requests with the same payload still create duplicate purchases. What does this demonstrate?

Implementing POST redirect in Django Hard
A. PRG protects duplicate writes only when CSRF middleware is disabled
B. PRG guarantees idempotency only when the redirect response has status 302
C. PRG fails because POST data must be copied into the redirected GET request
D. PRG prevents browser refresh resubmission but does not guarantee idempotent processing

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?

Building forms using Django Hard
A. Give each form a distinct auto_id pattern when validating
B. Give each form a distinct initial dictionary when rendering
C. Give each form a distinct label_suffix when binding
D. Give each form a distinct 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']?

Data validation with Django forms Hard
A. None, because disabled fields are excluded from cleaned_data
B. 17, because a disabled Django field uses its initial value
C. A validation error, because submitting any disabled field is forbidden
D. 999, because POST data always overrides field configuration