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 create database backups
B. To collect input from users
C. To install Python packages
D. To configure the web server

2 Which HTML element is used to create a form?

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

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

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

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

Using GET, POST and HTTP Easy
A. In the server log only
B. In the URL query string
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. GET
B. HEAD
C. POST
D. TRACE

6 Which Django request attribute identifies the HTTP method used?

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

7 Which Django object contains form values submitted using POST?

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

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

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

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

Building forms using Django Easy
A. As class attributes
B. As database queries
C. As template blocks
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.FileField
D. forms.BooleanField

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

Building forms using Django Easy
A. To generate forms from models
B. To generate URLs from views
C. To generate models from templates
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_ul }}
B. {{ form.as_p }}
C. {{ form.as_div }}
D. {{ form.as_table }}

13 What does CSRF stand for?

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

14 What is the goal of a CSRF attack?

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

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

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

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

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

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. 404 Not Found
B. 403 Forbidden
C. 200 OK
D. 301 Moved Permanently

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

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

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. redirect()
C. render()
D. include()

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

Data validation with Django forms Easy
A. form.submit()
B. form.is_valid()
C. form.render()
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 POST because every HTML form should submit privately
B. Use DELETE because old filter values must be removed
C. Use GET because the filter represents a read-only query
D. Use PUT because the filter updates the displayed products

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 JavaScript event listener
C. The input is placed outside the submitted <form> element
D. The input does not include a CSS class for form fields

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.GET.get("q")
B. request.FILES.get("q")
C. request.POST.get("q")
D. request.COOKIES.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.method == request.POST:
B. if request.POST == "POST":
C. if request.method == "POST":
D. if request.GET.get("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.getlist("skills")
B. request.POST.items("skills")
C. request.POST.values("skills")
D. request.POST.get("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.POST.is_valid())
B. form = ContactForm(request.GET or request.POST)
C. form = ContactForm(request.POST or None)
D. form = ContactForm(request.method 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. model = Book and fields = ["title", "publication_date"]
C. form = Book and include = ["title", "publication_date"]
D. model = Book and widgets = ["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 second <form> element around the submit action
B. A submit control such as <button type="submit">Save</button>
C. A script that serializes every field before submission
D. A hidden control containing the Python form class name

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 browser may automatically include the banking site's cookies
C. The malicious page can directly read every banking database row
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. Serving a static stylesheet through a cached HTTP response
B. Displaying a public article through an anonymous GET request
C. Validating a local form field before enabling its submit button
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 server cannot distinguish POST requests from static file requests
C. A browser always rewrites cross-site POST requests as trusted GET requests
D. An attacker can also cause a browser to submit a cross-site form using POST

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. Add csrf=True to the form's method attribute
D. Place {{ request.user }} inside the submitted <form>

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 refreshes the CSRF token and protects the action from replay attacks
C. It removes CSRF checking and exposes the update action to forged requests
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") before checking form validity
C. Return render(request, "success.html") after saving data
D. Return redirect("success") after saving valid 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.save() followed by redirect("article-detail", pk=article.pk)
B. article = form.is_valid() followed by redirect("article-detail", pk=article.pk)
C. article = request.POST followed by redirect("article-detail", pk=article.id)
D. article = form.cleaned_data followed by render("article-detail", article.pk)

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. cleaned_age(self)
B. clean_age(self)
C. validate_age(self)
D. is_valid_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 form's clean() method
B. In the template's {% csrf_token %} tag
C. In the view after calling form.save()
D. In the password widget's attributes

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.is_valid() and access the value only when validation succeeds
B. Call form.save() and then inspect the original submitted dictionary
C. Call form.has_changed() so Django accepts all submitted values
D. Call form.as_p() so Django converts the field into cleaned data

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 responses cannot redirect to another URL after processing
C. GET requests may be cached or prefetched despite being expected to be safe
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. list(request.GET.get('tag'))
B. request.GET.get('tag')
C. request.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 raises ValidationError because no search fields were supplied
B. The form is bound to an empty QueryDict and immediately validates
C. The form is unbound because the empty QueryDict is replaced by None
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 empty strings are omitted from bound data
D. The form is valid because 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?

Data validation with Django forms Hard
A. Form.clean() → clean_age() → Field.clean() → validators
B. clean_age() → to_python() → validators → Form.clean()
C. validators → to_python() → Form.clean() → clean_age()
D. to_python() → validate() → validators → clean_age() → 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 clean_start_date() before reading end_date
D. Raise ValidationError from Form.clean() after reading both cleaned values

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. Model uniqueness constraints may not be checked by the form
B. Submitted strings may no longer be converted to Python values
C. The form may silently switch from bound to unbound state
D. Required HTML attributes may disappear from rendered widgets

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.refresh_from_db() before assigning relationships
C. Call form.save_m2m() after the instance has a primary key
D. Call instance.full_clean() before saving any scalar fields

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(files=request.POST)
C. Construct UploadForm(request.FILES, request.GET)
D. Construct UploadForm(request.POST, request.FILES)

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. HTTP permits the attacker to read cookies belonging to every visited origin
C. Django copies the victim's session cookie into every submitted HTML field
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 prevents JavaScript from reading any token present in the DOM
D. It reduces secret leakage through compression-based side channels

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. Append the CSRF token only to the URL fragment
B. Send the session ID in the Authorization header
C. Set Access-Control-Allow-Origin in the request headers
D. Send the CSRF token in the 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?

CSRF support in Django Hard
A. Wrap the page view with require_http_methods
B. Decorate the page view with ensure_csrf_cookie
C. Enable SECURE_HSTS_INCLUDE_SUBDOMAINS
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 https://app.example.com to CORS_ALLOW_HEADERS
B. Add forms.example.net to ALLOWED_HOSTS only
C. Add app.example.com to CSRF_COOKIE_PATH
D. Add https://forms.example.net to CSRF_TRUSTED_ORIGINS

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

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. Render the bound form on invalid POST and redirect only after success
B. Return a success redirect while recording errors only in server logs
C. Redirect invalid POST data by placing every field in the query string
D. Store the complete form object permanently in the user's session

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 prevents browser refresh resubmission but does not guarantee idempotent processing
B. PRG guarantees idempotency only when the redirect response has status 302
C. PRG protects duplicate writes only when CSRF middleware is disabled
D. PRG fails because POST data must be copied into the redirected GET request

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 initial dictionary when rendering
B. Give each form a distinct auto_id pattern when validating
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. 999, because POST data always overrides field configuration
D. A validation error, because submitting any disabled field is forbidden