Unit 2: Views and URLs - Practice Quiz

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

1 Which Django file commonly contains the URL patterns for an application?

Creating views and mapping to URLs Easy
A. views.py
B. urls.py
C. admin.py
D. models.py

2 Which function is commonly used to define a URL pattern in modern Django?

Creating views and mapping to URLs Easy
A. filter()
B. save()
C. render()
D. path()

3 What is the main purpose of a Django view?

Creating views and mapping to URLs Easy
A. Define a database table structure
B. Configure the development server
C. Process a request and return a response
D. Create a static CSS stylesheet

4 What is normally the first parameter of a function-based Django view?

Creating views and view logic Easy
A. response
B. template
C. model
D. request

5 Which Django shortcut combines a template with context data and returns a response?

Creating views and view logic Easy
A. redirect()
B. render()
C. reverse()
D. include()

6 What is context data used for in a Django view?

Creating views and view logic Easy
A. Registering models with admin
B. Defining URL route patterns
C. Passing values to a template
D. Starting the Django server

7 Which HTTP method is commonly used to retrieve a web page?

HTTP requests Easy
A. DELETE
B. POST
C. GET
D. PUT

8 Which HTTP method is commonly used to submit form data that changes server data?

HTTP requests Easy
A. POST
B. GET
C. OPTIONS
D. HEAD

9 Which expression checks whether a Django request uses the POST method?

HTTP requests Easy
A. request.type == "POST"
B. request.method == "POST"
C. request.action == "POST"
D. request.status == "POST"

10 Which Django class can create a basic text response?

Creating Requests and Responses Easy
A. HttpRequest
B. HttpResponse
C. QuerySet
D. URLPattern

11 Which object represents an incoming request in a Django view?

Creating Requests and Responses Easy
A. HttpRequest
B. TemplateResponse
C. JsonResponse
D. HttpResponse

12 Which response class is designed to return JSON data in Django?

Creating Requests and Responses Easy
A. JsonResponse
B. URLResolver
C. HttpRequest
D. FileResponse

13 In the URL https://example.com/products/, what does https identify?

Understanding URLs Easy
A. The domain name
B. The route name
C. The URL scheme
D. The query value

14 What is the purpose of Django's urlpatterns list?

Understanding URLs Easy
A. Store static file settings
B. Store URL-to-view mappings
C. Store template context values
D. Store database model fields

15 Which route captures an integer named id in Django?

Mapping URLs with Params Easy
A. products/{int:id}/
B. products/<str:id>/
C. products/<int:id>/
D. products/[int:id]/

16 For the route articles/<int:year>/, how is the captured year normally supplied to the view?

Mapping URLs with Params Easy
A. As a request header
B. As a keyword argument
C. As a template filter
D. As a cookie value

17 Which Django path converter captures a non-empty text value without a slash?

Mapping URLs with Params Easy
A. int
B. uuid
C. str
D. slug

18 Which Django function is used when a URL route is written as a regular expression?

Regular expressions in URLs Easy
A. re_path()
B. render()
C. path()
D. resolve()

19 In a Django regular-expression URL pattern, what does \d+ match?

Regular expressions in URLs Easy
A. One or more letters
B. Exactly one slash
C. Exactly one space
D. One or more digits

20 Which HTTP status code means that a requested page was not found?

Error Handling Easy
A. 200
B. 500
C. 301
D. 404

21 A Django project contains an app named store with a view function named product_list. Which URL configuration correctly maps /products/ to this view?

Creating views and mapping to URLs Medium
A. path("products/", product_list())
B. path("products/", product_list)
C. url("products/", product_list())
D. path("products/", views.product_list)

22 Why is include("blog.urls") commonly used in a project's main urls.py file?

Creating views and mapping to URLs Medium
A. It automatically creates a view for each route
B. It converts all URLs into regular expressions
C. It imports every model from the app
D. It delegates matching to the app's URL configuration

23 A view should display all published articles, ordered from newest to oldest. Which queryset best implements this requirement?

Creating views and view logic Medium
A. Article.objects.filter(published=True).order_by("created_at")
B. Article.objects.all().order_by("published", "created_at")
C. Article.objects.filter(published=True).order_by("-created_at")
D. Article.objects.filter(published=False).order_by("-created_at")

24 A view receives a request and should return a template named dashboard.html with a variable named username. Which statement is appropriate?

Creating views and view logic Medium
A. return HttpResponse("dashboard.html", username)
B. return template("dashboard.html", username)
C. return render(request, "dashboard.html", {"username": username})
D. return redirect("dashboard.html", {"username": username})

25 A Django view should process a form only when the client submits data. Which condition is most appropriate?

HTTP requests Medium
A. if request.type == "POST":
B. if request.method == "GET":
C. if request.method == "POST":
D. if request.data == "POST":

26 Which request attribute is generally used to access values submitted through an HTML form using the POST method?

HTTP requests Medium
A. request.BODY
B. request.GET
C. request.FORM
D. request.POST

27 A view needs to read the page value from a URL such as /articles/?page=3. Which expression retrieves it?

HTTP requests Medium
A. request.path.get("page")
B. request.POST.get("page")
C. request.GET.get("page")
D. request.params.get("page")

28 Which response correctly returns JSON data from a Django view?

Creating Requests and Responses Medium
A. return JsonResponse({"status": "ok"})
B. return HttpResponse({"status": "ok"})
C. return redirect({"status": "ok"})
D. return render({"status": "ok"})

29 A view must return a plain-text response with the exact content Service available. Which implementation is suitable?

Creating Requests and Responses Medium
A. return JsonResponse("Service available")
B. return HttpResponse("Service available")
C. return render("Service available")
D. return request("Service available")

30 A successful form submission should redirect to the named URL pattern order-confirmation. Why is redirecting preferable to rendering the same form immediately?

Creating Requests and Responses Medium
A. It avoids duplicate submissions after a page refresh
B. It removes the need for a URL pattern
C. It automatically validates every model field
D. It prevents the browser from sending any request

31 In the URL /shop/items/?category=books, which part is the query string?

Understanding URLs Medium
A. /shop/
B. ?category=books
C. shop/items/
D. items/

32 What is the main purpose of assigning a name to a Django URL pattern?

Understanding URLs Medium
A. To determine the HTTP request method
B. To create a database table
C. To reference the URL without hardcoding its path
D. To restrict the URL to administrators

33 Given path("users/<int:user_id>/", views.profile, name="profile"), what value is passed to the view for /users/42/?

Understanding URLs Medium
A. The string users
B. The integer 42
C. The string user_id
D. The integer 1

34 Which view signature matches the URL pattern path("products/<slug:code>/", views.detail)?

Mapping URLs with Params Medium
A. def detail(request, slug):
B. def detail(request, id):
C. def detail(product, request):
D. def detail(request, code):

35 Which URL pattern captures an optional numeric page parameter using two separate routes?

Mapping URLs with Params Medium
A. path("reports/", views.reports), path("reports/<int:page>/", views.reports)
B. path("reports/<page:int?>/", views.reports)
C. path("reports/[int:page]/", views.reports)
D. path("reports/<int:page>/", views.reports)

36 A URL pattern is defined as path("orders/<uuid:order_id>/", views.order_detail). Which request can match it?

Mapping URLs with Params Medium
A. /orders/550e8400-e29b-41d4-a716-446655440000/
B. /orders/abc-def/
C. /orders/order-550e8400/
D. /orders/12345/

37 In a regex-based Django URL pattern, what does the expression (?P<year>[0-9]{4}) do?

Regular expressions in URLs Medium
A. Matches any four characters as year
B. Requires the literal text year
C. Captures one digit as year
D. Captures four digits as year

38 A URL pattern uses the regular expression r"^archive/(?P<year>[0-9]{4})/$". Which URL matches it?

Regular expressions in URLs Medium
A. /archive/2024/articles/
B. /archive/24/
C. /archive/year/
D. /archive/2024/

39 A detail view uses Product.objects.get(pk=product_id). What is a common Django approach for returning a 404 response when the object does not exist?

Error Handling Medium
A. Use HttpResponseNotFound(Product, pk=product_id)
B. Use redirect(Product, pk=product_id)
C. Use render_404(Product, pk=product_id)
D. Use get_object_or_404(Product, pk=product_id)

40 A view converts request.GET.get("quantity") to an integer. What should it do when the value is missing or nonnumeric?

Error Handling Medium
A. Convert the value to a list first
B. Assume the conversion always succeeds
C. Redirect every request to the home page
D. Catch the conversion error and return a suitable response

41 Given these URL patterns in order:

path('item/<slug:key>/', slug_view)

path('item/<int:key>/', integer_view)

Which result occurs for a request to /item/123/?

Creating views and mapping to URLs Hard
A. Django returns a 404 response.
B. Django raises an ambiguous-match error.
C. integer_view receives key=123.
D. slug_view receives key='123'.

42 The root URLconf contains path('shop/<int:store_id>/', include('catalog.urls')), while catalog.urls contains path('item/<int:item_id>/', views.item). What keyword arguments are supplied to views.item for /shop/8/item/21/?

Mapping URLs with Params Hard
A. store_id=8 and item_id=21
B. args=(8, 21) with no keyword arguments
C. Only item_id=21
D. Only store_id=8

43 Consider path('archive/<int:year>/', views.archive, {'year': 2000}). Which value does views.archive(request, year) receive for /archive/2024/?

Mapping URLs with Params Hard
A. A TypeError, because the keyword argument is supplied twice
B. 2024, because captured URL parameters override default arguments
C. 2000, because the extra keyword argument overrides the captured value
D. Both values as a two-element positional argument tuple

44 Suppose catalog.urls declares app_name = 'catalog' and names a pattern detail. It is included using path('store/', include('catalog.urls', namespace='west')). Which call correctly generates the URL for object pk=7?

Understanding URLs Hard
A. reverse('west:detail', kwargs={'pk': 7})
B. reverse('catalog:west:detail', kwargs={'pk': 7})
C. reverse('catalog:detail', namespace='west', pk=7)
D. reverse('west.catalog.detail', args=[7])

45 A URLconf defines re_path(r'^(foo|bar)/$', views.choice, name='choice'). Incoming requests match correctly. What generally happens when code calls reverse('choice', args=['foo'])?

Regular expressions in URLs Hard
A. It raises Resolver404 because positional arguments cannot be used.
B. It returns /foo/ by selecting the matching regular-expression branch.
C. It raises NoReverseMatch because alternation with | is not reversible.
D. It returns /(foo|bar)/ because the expression is preserved literally.

46 The root URLconf uses re_path(r'^api/$', include('api.urls')), and api.urls contains path('items/', views.items). Why does /api/items/ fail to reach the view?

Regular expressions in URLs Hard
A. The child route must repeat the api/ prefix.
B. The parent expression ends with $, forcing a complete match at api/.
C. include() cannot be used with re_path() patterns.
D. A regular-expression parent cannot include a path() child.

47 For the route path('files/<path:rest>/', views.file_view), which statement accurately describes matching behavior?

Understanding URLs Hard
A. /files/a/b/ fails because converters never accept embedded slashes.
B. /files/ matches with rest='', but nested paths do not match.
C. /files/a/b/ matches with rest='a/b', but /files/ does not match.
D. /files/a/b/ matches with rest=['a', 'b'] as a list.

48 For a request ending in ?tag=python&tag=django, what do request.GET['tag'] and request.GET.getlist('tag') return?

HTTP requests Hard
A. ['python', 'django'] and 'django'
B. 'python' and ['python', 'django']
C. 'python,django' and ['python,django']
D. 'django' and ['python', 'django']

49 A view executes chunk = request.read() and later evaluates request.body, without having accessed request.body earlier. What is the expected result?

HTTP requests Hard
A. Django raises RawPostDataException because the request stream was already consumed.
B. Django returns the same bytes by automatically rewinding the request stream.
C. Django returns b'' because reading the stream silently empties the body property.
D. Django reparses the payload and stores it in request.POST.

50 A client sends a valid JSON object using POST with Content-Type: application/json. No custom middleware parses the payload. Which statement is correct?

HTTP requests Hard
A. request.FILES contains the JSON payload as an uploaded in-memory file.
B. request.GET contains the JSON because non-form bodies are treated as query data.
C. request.POST is empty, and the JSON must be decoded from request.body.
D. request.POST contains the decoded JSON keys as a mutable dictionary.

51 A function view is decorated with @require_http_methods(['GET', 'POST']). What happens when it receives a HEAD request?

Creating views and view logic Hard
A. It executes as POST but suppresses the response body.
B. It executes as GET because HTTP automatically aliases HEAD to GET.
C. It returns HTTP 405 because HEAD was not explicitly allowed.
D. It returns HTTP 204 without invoking the decorated view.

52 Which response correctly returns a top-level JSON array from a Django view using JsonResponse?

Creating Requests and Responses Hard
A. JsonResponse('[1, 2, 3]', safe=True)
B. JsonResponse({'data': [1, 2, 3]}, safe=False)
C. JsonResponse([1, 2, 3], safe=False)
D. JsonResponse([1, 2, 3], safe=True)

53 Middleware attempts to log response.content for every response. What must it account for when a view returns StreamingHttpResponse?

Creating Requests and Responses Hard
A. Streaming responses lack usable content; the body is exposed through streaming_content.
B. Streaming responses expose bytes through body instead of content.
C. Streaming responses store the complete body in content after view execution.
D. Streaming responses convert to HttpResponse when middleware accesses content.

54 Why is this download view unsafe?

with open(path, 'rb') as file_obj:

return FileResponse(file_obj)

Creating Requests and Responses Hard
A. Binary mode prevents Django from determining the response length.
B. The response is streamed before the return statement completes.
C. The context manager closes the file before the response is streamed.
D. FileResponse accepts paths but never accepts open file objects.

55 With DEBUG=False, which definition is suitable for a custom 404 handler referenced by handler404 in the root URLconf?

Error Handling Hard
A. def not_found(request): return render(request, '404.html', status=404)
B. def not_found(request, exception): return render(request, '404.html', status=200)
C. def not_found(exception): return render(exception, '404.html', status=404)
D. def not_found(request, exception): return render(request, '404.html', status=404)

56 A view raises django.core.exceptions.PermissionDenied, and the exception is not caught by application code. With standard Django error handling, which outcome is expected?

Error Handling Hard
A. Django converts the exception into a 401 authentication challenge.
B. Django invokes 404 handling to conceal the protected resource.
C. Django invokes 500 handling because all raised exceptions are server errors.
D. Django invokes 403 handling and returns a forbidden response.

57 What normally happens when an uncaught SuspiciousOperation reaches Django's top-level request handler?

Error Handling Hard
A. It is converted to HTTP 404 to hide malformed request details.
B. It is converted to HTTP 403 without being logged.
C. It is logged as a security-related event and converted to HTTP 400.
D. It is passed to handler500 and converted to HTTP 500.

58 Which exception pairing correctly describes failures of resolve('/missing/') and reverse('missing-name')?

Error Handling Hard
A. ValueError for resolve() and KeyError for reverse()
B. Resolver404 for resolve() and NoReverseMatch for reverse()
C. Http404 for both operations
D. NoReverseMatch for resolve() and Resolver404 for reverse()

59 A custom even path converter matches digits in its regex but raises ValueError from to_python() for odd numbers. The patterns are ordered as path('n/<even:x>/', even_view) followed by path('n/<int:x>/', integer_view). What happens for /n/7/?

Creating views and mapping to URLs Hard
A. Django immediately returns HTTP 500 because conversion raised ValueError.
B. Django calls even_view with the original string x='7'.
C. Django immediately returns HTTP 404 without checking later patterns.
D. Django rejects the first match and calls integer_view with x=7.

60 What happens if code calls reverse('detail', args=[7], kwargs={'pk': 7})?

Understanding URLs Hard
A. Django uses both values to test multiple candidate URL patterns.
B. Django raises ValueError because positional and keyword arguments cannot be mixed.
C. Django prefers kwargs and silently ignores the positional argument.
D. Django prefers args and silently ignores the keyword argument.