Unit 2: Views and URLs - Practice Quiz
1 Which Django file commonly contains the URL patterns for an application?
views.py
urls.py
admin.py
models.py
2 Which function is commonly used to define a URL pattern in modern Django?
filter()
save()
render()
path()
3 What is the main purpose of a Django view?
4 What is normally the first parameter of a function-based Django view?
response
template
model
request
5 Which Django shortcut combines a template with context data and returns a response?
redirect()
render()
reverse()
include()
6 What is context data used for in a Django view?
7 Which HTTP method is commonly used to retrieve a web page?
8 Which HTTP method is commonly used to submit form data that changes server data?
9 Which expression checks whether a Django request uses the POST method?
request.type == "POST"
request.method == "POST"
request.action == "POST"
request.status == "POST"
10 Which Django class can create a basic text response?
HttpRequest
HttpResponse
QuerySet
URLPattern
11 Which object represents an incoming request in a Django view?
HttpRequest
TemplateResponse
JsonResponse
HttpResponse
12 Which response class is designed to return JSON data in Django?
JsonResponse
URLResolver
HttpRequest
FileResponse
13
In the URL https://example.com/products/, what does https identify?
14
What is the purpose of Django's urlpatterns list?
15
Which route captures an integer named id in Django?
products/{int:id}/
products/<str:id>/
products/<int:id>/
products/[int:id]/
16
For the route articles/<int:year>/, how is the captured year normally supplied to the view?
17 Which Django path converter captures a non-empty text value without a slash?
int
uuid
str
slug
18 Which Django function is used when a URL route is written as a regular expression?
re_path()
render()
path()
resolve()
19
In a Django regular-expression URL pattern, what does \d+ match?
20 Which HTTP status code means that a requested page was not found?
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?
path("products/", product_list())
path("products/", product_list)
url("products/", product_list())
path("products/", views.product_list)
22
Why is include("blog.urls") commonly used in a project's main urls.py file?
23 A view should display all published articles, ordered from newest to oldest. Which queryset best implements this requirement?
Article.objects.filter(published=True).order_by("created_at")
Article.objects.all().order_by("published", "created_at")
Article.objects.filter(published=True).order_by("-created_at")
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?
return HttpResponse("dashboard.html", username)
return template("dashboard.html", username)
return render(request, "dashboard.html", {"username": username})
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?
if request.type == "POST":
if request.method == "GET":
if request.method == "POST":
if request.data == "POST":
26
Which request attribute is generally used to access values submitted through an HTML form using the POST method?
request.BODY
request.GET
request.FORM
request.POST
27
A view needs to read the page value from a URL such as /articles/?page=3. Which expression retrieves it?
request.path.get("page")
request.POST.get("page")
request.GET.get("page")
request.params.get("page")
28 Which response correctly returns JSON data from a Django view?
return JsonResponse({"status": "ok"})
return HttpResponse({"status": "ok"})
return redirect({"status": "ok"})
return render({"status": "ok"})
29
A view must return a plain-text response with the exact content Service available. Which implementation is suitable?
return JsonResponse("Service available")
return HttpResponse("Service available")
return render("Service available")
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?
31
In the URL /shop/items/?category=books, which part is the query string?
/shop/
?category=books
shop/items/
items/
32
What is the main purpose of assigning a name to a Django URL pattern?
33
Given path("users/<int:user_id>/", views.profile, name="profile"), what value is passed to the view for /users/42/?
users
42
user_id
1
34
Which view signature matches the URL pattern path("products/<slug:code>/", views.detail)?
def detail(request, slug):
def detail(request, id):
def detail(product, request):
def detail(request, code):
35
Which URL pattern captures an optional numeric page parameter using two separate routes?
path("reports/", views.reports), path("reports/<int:page>/", views.reports)
path("reports/<page:int?>/", views.reports)
path("reports/[int:page]/", views.reports)
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?
/orders/550e8400-e29b-41d4-a716-446655440000/
/orders/abc-def/
/orders/order-550e8400/
/orders/12345/
37
In a regex-based Django URL pattern, what does the expression (?P<year>[0-9]{4}) do?
year
year
year
year
38
A URL pattern uses the regular expression r"^archive/(?P<year>[0-9]{4})/$". Which URL matches it?
/archive/2024/articles/
/archive/24/
/archive/year/
/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?
HttpResponseNotFound(Product, pk=product_id)
redirect(Product, pk=product_id)
render_404(Product, pk=product_id)
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?
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/?
integer_view receives key=123.
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/?
store_id=8 and item_id=21
args=(8, 21) with no keyword arguments
item_id=21
store_id=8
43
Consider path('archive/<int:year>/', views.archive, {'year': 2000}). Which value does views.archive(request, year) receive for /archive/2024/?
TypeError, because the keyword argument is supplied twice
2024, because captured URL parameters override default arguments
2000, because the extra keyword argument overrides the captured value
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?
reverse('west:detail', kwargs={'pk': 7})
reverse('catalog:west:detail', kwargs={'pk': 7})
reverse('catalog:detail', namespace='west', pk=7)
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'])?
Resolver404 because positional arguments cannot be used.
/foo/ by selecting the matching regular-expression branch.
NoReverseMatch because alternation with | is not reversible.
/(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?
api/ prefix.
$, forcing a complete match at api/.
include() cannot be used with re_path() patterns.
path() child.
47
For the route path('files/<path:rest>/', views.file_view), which statement accurately describes matching behavior?
/files/a/b/ fails because converters never accept embedded slashes.
/files/ matches with rest='', but nested paths do not match.
/files/a/b/ matches with rest='a/b', but /files/ does not match.
/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?
['python', 'django'] and 'django'
'python' and ['python', 'django']
'python,django' and ['python,django']
'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?
RawPostDataException because the request stream was already consumed.
b'' because reading the stream silently empties the body property.
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?
request.FILES contains the JSON payload as an uploaded in-memory file.
request.GET contains the JSON because non-form bodies are treated as query data.
request.POST is empty, and the JSON must be decoded from request.body.
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?
POST but suppresses the response body.
GET because HTTP automatically aliases HEAD to GET.
HEAD was not explicitly allowed.
52
Which response correctly returns a top-level JSON array from a Django view using JsonResponse?
JsonResponse('[1, 2, 3]', safe=True)
JsonResponse({'data': [1, 2, 3]}, safe=False)
JsonResponse([1, 2, 3], safe=False)
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?
content; the body is exposed through streaming_content.
body instead of content.
content after view execution.
HttpResponse when middleware accesses content.
54
Why is this download view unsafe?
with open(path, 'rb') as file_obj:
return FileResponse(file_obj)
return statement completes.
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?
def not_found(request): return render(request, '404.html', status=404)
def not_found(request, exception): return render(request, '404.html', status=200)
def not_found(exception): return render(exception, '404.html', status=404)
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?
57
What normally happens when an uncaught SuspiciousOperation reaches Django's top-level request handler?
handler500 and converted to HTTP 500.
58
Which exception pairing correctly describes failures of resolve('/missing/') and reverse('missing-name')?
ValueError for resolve() and KeyError for reverse()
Resolver404 for resolve() and NoReverseMatch for reverse()
Http404 for both operations
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/?
ValueError.
even_view with the original string x='7'.
integer_view with x=7.
60
What happens if code calls reverse('detail', args=[7], kwargs={'pk': 7})?
ValueError because positional and keyword arguments cannot be mixed.
kwargs and silently ignores the positional argument.
args and silently ignores the keyword argument.
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 →