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. admin.py
C. models.py
D. urls.py

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

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

3 What is the main purpose of a Django view?

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

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

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

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

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

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. Starting the Django server
D. Passing values to a template

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

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

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

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

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

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

10 Which Django class can create a basic text response?

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

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

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

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

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

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

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

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

Understanding URLs Easy
A. Store URL-to-view mappings
B. Store template context values
C. Store static file settings
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/<int:id>/
C. products/{int:id}/
D. products/<str: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 template filter
B. As a keyword argument
C. As a cookie value
D. As a request header

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

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

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

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

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

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

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

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

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/", views.product_list)
B. path("products/", product_list)
C. path("products/", product_list())
D. url("products/", 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 delegates matching to the app's URL configuration
B. It converts all URLs into regular expressions
C. It imports every model from the app
D. It automatically creates a view for each route

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.filter(published=False).order_by("-created_at")
C. Article.objects.all().order_by("published", "created_at")
D. Article.objects.filter(published=True).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 redirect("dashboard.html", {"username": username})
B. return HttpResponse("dashboard.html", username)
C. return template("dashboard.html", username)
D. return render(request, "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.data == "POST":
B. if request.method == "GET":
C. if request.type == "POST":
D. if request.method == "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.GET
B. request.BODY
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.params.get("page")
B. request.path.get("page")
C. request.POST.get("page")
D. request.GET.get("page")

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

Creating Requests and Responses Medium
A. return HttpResponse({"status": "ok"})
B. return JsonResponse({"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 HttpResponse("Service available")
B. return render("Service available")
C. return JsonResponse("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 prevents the browser from sending any request
B. It automatically validates every model field
C. It removes the need for a URL pattern
D. It avoids duplicate submissions after a page refresh

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

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

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

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

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 user_id
B. The integer 1
C. The integer 42
D. The string users

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

Mapping URLs with Params Medium
A. def detail(product, request):
B. def detail(request, id):
C. def detail(request, slug):
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/[int:page]/", views.reports)
B. path("reports/<page:int?>/", views.reports)
C. path("reports/", views.reports), 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/abc-def/
B. /orders/12345/
C. /orders/550e8400-e29b-41d4-a716-446655440000/
D. /orders/order-550e8400/

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

Regular expressions in URLs Medium
A. Requires the literal text year
B. Captures four digits as year
C. Captures one digit as year
D. Matches any four characters 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/
B. /archive/24/
C. /archive/year/
D. /archive/2024/articles/

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 get_object_or_404(Product, pk=product_id)
B. Use HttpResponseNotFound(Product, pk=product_id)
C. Use redirect(Product, pk=product_id)
D. Use render_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. Catch the conversion error and return a suitable response
B. Assume the conversion always succeeds
C. Convert the value to a list first
D. Redirect every request to the home page

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. args=(8, 21) with no keyword arguments
B. store_id=8 and item_id=21
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. 2000, because the extra keyword argument overrides the captured value
C. Both values as a two-element positional argument tuple
D. 2024, because captured URL parameters override default arguments

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 returns /foo/ by selecting the matching regular-expression branch.
B. It raises NoReverseMatch because alternation with | is not reversible.
C. It returns /(foo|bar)/ because the expression is preserved literally.
D. It raises Resolver404 because positional arguments cannot be used.

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. include() cannot be used with re_path() patterns.
B. The parent expression ends with $, forcing a complete match at api/.
C. The child route must repeat the api/ prefix.
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/ matches with rest=['a', 'b'] as a list.
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/ fails because converters never accept embedded slashes.

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. 'django' and ['python', 'django']
B. 'python' and ['python', 'django']
C. ['python', 'django'] and 'django'
D. 'python,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 returns the same bytes by automatically rewinding the request stream.
B. Django returns b'' because reading the stream silently empties the body property.
C. Django raises RawPostDataException because the request stream was already consumed.
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.POST contains the decoded JSON keys as a mutable dictionary.
B. request.GET contains the JSON because non-form bodies are treated as query data.
C. request.FILES contains the JSON payload as an uploaded in-memory file.
D. request.POST is empty, and the JSON must be decoded from request.body.

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 GET because HTTP automatically aliases HEAD to GET.
B. It executes as POST but suppresses the response body.
C. It returns HTTP 204 without invoking the decorated view.
D. It returns HTTP 405 because HEAD was not explicitly allowed.

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([1, 2, 3], safe=False)
C. JsonResponse({'data': [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 convert to HttpResponse when middleware accesses content.
C. Streaming responses expose bytes through body instead of content.
D. Streaming responses store the complete body in content after view execution.

54 Why is this download view unsafe?

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

return FileResponse(file_obj)

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

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(exception): return render(exception, '404.html', status=404)
B. def not_found(request, exception): return render(request, '404.html', status=404)
C. def not_found(request): return render(request, '404.html', status=404)
D. def not_found(request, exception): return render(request, '404.html', status=200)

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 passed to handler500 and converted to HTTP 500.
C. It is converted to HTTP 403 without being logged.
D. It is logged as a security-related event and converted to HTTP 400.

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

Error Handling Hard
A. NoReverseMatch for resolve() and Resolver404 for reverse()
B. Http404 for both operations
C. Resolver404 for resolve() and NoReverseMatch for reverse()
D. ValueError for resolve() and KeyError 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 404 without checking later patterns.
B. Django rejects the first match and calls integer_view with x=7.
C. Django calls even_view with the original string x='7'.
D. Django immediately returns HTTP 500 because conversion raised ValueError.

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

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