Unit 2: Views and URLs - Practice Quiz
1 Which Django file commonly contains the URL patterns for an application?
views.py
admin.py
models.py
urls.py
2 Which function is commonly used to define a URL pattern in modern Django?
render()
path()
save()
filter()
3 What is the main purpose of a Django view?
4 What is normally the first parameter of a function-based Django view?
request
response
template
model
5 Which Django shortcut combines a template with context data and returns a response?
render()
redirect()
include()
reverse()
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.action == "POST"
request.status == "POST"
request.method == "POST"
request.type == "POST"
10 Which Django class can create a basic text response?
HttpRequest
URLPattern
HttpResponse
QuerySet
11 Which object represents an incoming request in a Django view?
JsonResponse
HttpResponse
TemplateResponse
HttpRequest
12 Which response class is designed to return JSON data in Django?
JsonResponse
HttpRequest
URLResolver
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/<int:id>/
products/{int:id}/
products/<str: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?
slug
uuid
str
int
18 Which Django function is used when a URL route is written as a regular expression?
render()
resolve()
path()
re_path()
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/", views.product_list)
path("products/", product_list)
path("products/", product_list())
url("products/", 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.filter(published=False).order_by("-created_at")
Article.objects.all().order_by("published", "created_at")
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?
return redirect("dashboard.html", {"username": username})
return HttpResponse("dashboard.html", username)
return template("dashboard.html", username)
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?
if request.data == "POST":
if request.method == "GET":
if request.type == "POST":
if request.method == "POST":
26
Which request attribute is generally used to access values submitted through an HTML form using the POST method?
request.GET
request.BODY
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.params.get("page")
request.path.get("page")
request.POST.get("page")
request.GET.get("page")
28 Which response correctly returns JSON data from a Django view?
return HttpResponse({"status": "ok"})
return JsonResponse({"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 HttpResponse("Service available")
return render("Service available")
return JsonResponse("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?
items/
?category=books
/shop/
shop/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/?
user_id
1
42
users
34
Which view signature matches the URL pattern path("products/<slug:code>/", views.detail)?
def detail(product, request):
def detail(request, id):
def detail(request, slug):
def detail(request, code):
35
Which URL pattern captures an optional numeric page parameter using two separate routes?
path("reports/[int:page]/", views.reports)
path("reports/<page:int?>/", views.reports)
path("reports/", 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/abc-def/
/orders/12345/
/orders/550e8400-e29b-41d4-a716-446655440000/
/orders/order-550e8400/
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/
/archive/24/
/archive/year/
/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?
get_object_or_404(Product, pk=product_id)
HttpResponseNotFound(Product, pk=product_id)
redirect(Product, pk=product_id)
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?
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/?
args=(8, 21) with no keyword arguments
store_id=8 and item_id=21
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
2000, because the extra keyword argument overrides the captured value
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?
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'])?
/foo/ by selecting the matching regular-expression branch.
NoReverseMatch because alternation with | is not reversible.
/(foo|bar)/ because the expression is preserved literally.
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?
include() cannot be used with re_path() patterns.
$, forcing a complete match at api/.
api/ prefix.
path() child.
47
For the route path('files/<path:rest>/', views.file_view), which statement accurately describes matching behavior?
/files/a/b/ matches with rest=['a', 'b'] as a list.
/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/ 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?
'django' and ['python', 'django']
'python' and ['python', 'django']
['python', 'django'] and 'django'
'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?
b'' because reading the stream silently empties the body property.
RawPostDataException because the request stream was already consumed.
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.POST contains the decoded JSON keys as a mutable dictionary.
request.GET contains the JSON because non-form bodies are treated as query data.
request.FILES contains the JSON payload as an uploaded in-memory file.
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?
GET because HTTP automatically aliases HEAD to GET.
POST but suppresses the response body.
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([1, 2, 3], safe=False)
JsonResponse({'data': [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.
HttpResponse when middleware accesses content.
body instead of content.
content after view execution.
54
Why is this download view unsafe?
with open(path, 'rb') as file_obj:
return FileResponse(file_obj)
FileResponse accepts paths but never accepts open file objects.
return statement completes.
55
With DEBUG=False, which definition is suitable for a custom 404 handler referenced by handler404 in the root URLconf?
def not_found(exception): return render(exception, '404.html', status=404)
def not_found(request, exception): return render(request, '404.html', status=404)
def not_found(request): return render(request, '404.html', status=404)
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?
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')?
NoReverseMatch for resolve() and Resolver404 for reverse()
Http404 for both operations
Resolver404 for resolve() and NoReverseMatch for reverse()
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/?
integer_view with x=7.
even_view with the original string x='7'.
ValueError.
60
What happens if code calls reverse('detail', args=[7], kwargs={'pk': 7})?
args and silently ignores the keyword argument.
ValueError because positional and keyword arguments cannot be mixed.
kwargs and silently ignores the positional 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 →