Unit 2: Views and URLs - Subjective Questions
INT253 — Web Development In Python Using Django • Practice Questions with Detailed Answers
20 questions
Define a view in Django. Explain its role in processing a web request.
A view is a Python function or class that receives an HTTP request and returns an HTTP response.
The role of a view includes:
- Receiving an
HttpRequestobject from Django. - Executing application logic, such as retrieving data from a database.
- Processing form data or URL parameters.
- Selecting and rendering an HTML template when required.
- Returning an
HttpResponse, redirect, JSON response, or error response.
Example:
from django.http import HttpResponse
def home(request):
return HttpResponse('Welcome to the home page')When a URL is mapped to home, Django calls this function and sends the returned response to the browser.
Describe the steps required to create a Django view and map it to a URL.
The main steps are:
- Create the view: Define a function in
views.pythat accepts a request and returns a response.
from django.http import HttpResponse
def about(request):
return HttpResponse('About our website')- Create the application URL configuration: Add a
urls.pyfile to the application.
from django.urls import path
from . import views
urlpatterns = [
path('about/', views.about, name='about'),
]- Include application URLs in the project URL configuration:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]- Run the server: Visit
/about/in the browser. Django matches the path and executes theaboutview.
Explain how view logic is implemented in a Django function-based view.
A function-based view implements view logic through normal Python statements. It accepts an HttpRequest, performs the required processing, and returns an HttpResponse.
View logic may include:
- Checking the HTTP request method.
- Reading query-string or form parameters.
- Validating user input.
- Retrieving or modifying database records.
- Selecting a template.
- Preparing a context dictionary.
- Returning success, redirect, or error responses.
Example:
from django.http import HttpResponse
def greeting(request):
name = request.GET.get('name', 'Guest')
if name.strip() == '':
name = 'Guest'
return HttpResponse(f'Hello, {name}!')Here, the view reads a query parameter, applies a default value, validates it, and creates a dynamic response.
What is an HttpRequest object in Django? Describe its commonly used attributes.
An HttpRequest object represents the HTTP request sent by a client to the Django server. Django creates this object automatically and passes it as the first argument to a view.
Common attributes include:
request.method: Contains the request method, such asGETorPOST.request.GET: A dictionary-likeQueryDictcontaining query-string parameters.request.POST: AQueryDictcontaining submitted form data from a POST request.request.FILES: Contains uploaded files.request.path: Contains the requested URL path.request.user: Represents the currently authenticated user.request.session: Provides access to session data.request.COOKIES: Contains cookies sent by the browser.request.headers: Provides access to HTTP request headers.
These attributes allow a view to understand and process client input.
Distinguish between HTTP GET and POST requests in the context of Django views.
GET and POST are HTTP methods used for different purposes.
| Basis | GET | POST |
|---|---|---|
| Purpose | Retrieves data | Submits or modifies data |
| Data location | Query string in the URL | Request body |
| Django access | request.GET |
request.POST |
| Visibility | Parameters are visible in the URL | Parameters are not normally visible in the URL |
| Bookmarking | Can usually be bookmarked | Cannot normally be bookmarked with submitted data |
| Typical use | Search, filtering, page selection | Login, registration, create/update operations |
Example view logic:
def contact(request):
if request.method == 'POST':
message = request.POST.get('message')
# Process submitted data
else:
# Display the form
passA POST request should normally include CSRF protection through {% csrf_token %} in a Django template.
Explain how Django creates an HTTP response using HttpResponse. Give suitable examples.
HttpResponse is a Django class used to construct and return an HTTP response from a view. It can contain text, HTML, or other content and may specify a status code and content type.
Basic example:
from django.http import HttpResponse
def home(request):
return HttpResponse('<h1>Home Page</h1>')Response with a content type:
def text_file(request):
return HttpResponse('Report content', content_type='text/plain')Response with a status code:
def unavailable(request):
return HttpResponse('Service unavailable', status=503)Important features are:
- The response body contains the content sent to the client.
content_typeidentifies the media type.statusspecifies the HTTP status code.- Response headers can be added using dictionary-style assignment, such as
response['X-App-Version'] = '1.0'.
Compare HttpResponse and the render() shortcut in Django.
HttpResponse and render() both return response objects, but they are used differently.
HttpResponse:
- Directly returns text, HTML, or other content.
- Does not automatically load a template.
- Is useful for short responses, generated files, or simple testing.
return HttpResponse('Hello')render():
- Loads a template.
- Combines the template with a context dictionary.
- Returns the resulting
HttpResponse. - Is preferred for normal HTML pages.
from django.shortcuts import render
def profile(request):
context = {'username': 'Asha'}
return render(request, 'profile.html', context)Thus, render() is effectively a convenient shortcut for loading a template, rendering it with context, and placing the result in an HttpResponse.
Explain the structure and purpose of a Django URL configuration.
A Django URL configuration, commonly called a URLconf, maps URL patterns to views. It is usually stored in a file named urls.py.
Example:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
]Its main components are:
urlpatterns: A list containing URL pattern objects.- Route: A string such as
'contact/'that Django tries to match. - View: The function or class executed after a successful match.
- Name: An optional identifier used for URL reversing.
Django checks patterns from top to bottom. When it finds the first matching pattern, it calls the associated view. If no pattern matches, Django normally returns a 404 Not Found response.
What is the purpose of include() in Django URL mapping? Explain with an example.
The include() function connects an application's URL configuration to the main project URL configuration. It supports modularity by allowing each application to maintain its own urls.py file.
Project-level urls.py:
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')),
]Application-level blog/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('create/', views.create_post, name='create_post'),
]The complete URLs become:
/blog/forpost_list/blog/create/forcreate_post
Benefits include:
- Better organization.
- Reusable applications.
- Shorter project URL configuration.
- Easier maintenance and testing.
Describe how dynamic URL parameters are captured and passed to Django views.
Dynamic URL parameters are variable parts of a URL. Django captures them using path converters and passes them to the view as keyword arguments.
URL pattern:
from django.urls import path
from . import views
urlpatterns = [
path('student/<int:student_id>/', views.student_detail, name='student_detail'),
]View:
from django.http import HttpResponse
def student_detail(request, student_id):
return HttpResponse(f'Student ID: {student_id}')For /student/25/, Django converts 25 into an integer and calls the view with student_id=25.
Important points:
- The parameter name in the URL must correspond to a view parameter.
- The converter validates and converts the value.
- Multiple parameters may be captured in one URL.
- Named parameters improve readability and make view logic easier to understand.
Explain the built-in path converters available in Django URL patterns.
Django provides path converters to capture and validate URL values.
str: Matches any non-empty string excluding/. It is the default converter.int: Matches zero or positive integers and converts the result toint.slug: Matches letters, numbers, hyphens, and underscores.uuid: Matches a formatted UUID and converts it to a UUID object.path: Matches a non-empty string including/characters.
Examples:
path('category/<str:name>/', views.category)
path('product/<int:product_id>/', views.product)
path('article/<slug:article_slug>/', views.article)
path('record/<uuid:record_id>/', views.record)
path('file/<path:file_path>/', views.file_view)Converters make URL patterns clear and ensure that views receive values in appropriate Python types.
Differentiate between URL path parameters and query-string parameters in Django.
Both mechanisms pass values through a URL, but they have different roles.
Path parameters:
- Form part of the URL path.
- Are declared in
path()orre_path(). - Are passed directly as arguments to the view.
- Usually identify a specific resource.
Example URL: /books/12/
path('books/<int:book_id>/', views.book_detail)The value is received as book_id.
Query-string parameters:
- Appear after
?in the URL. - Are accessed through
request.GET. - Are commonly used for filtering, searching, sorting, and pagination.
Example URL: /books/?category=python&page=2
category = request.GET.get('category')
page = request.GET.get('page', '1')Path parameters normally identify what resource is requested, while query parameters modify how a collection or response is displayed.
Explain named URL patterns and URL reversing in Django. Why should hard-coded URLs be avoided?
A named URL pattern assigns a stable identifier to a route.
path('products/<int:product_id>/', views.product_detail, name='product_detail')The URL can then be generated by its name rather than written manually.
In Python:
from django.urls import reverse
url = reverse('product_detail', kwargs={'product_id': 10})In a template:
<a href="{% url 'product_detail' product_id=10 %}">View product</a>Hard-coded URLs should be avoided because:
- A route change would require changes in many files.
- Typing mistakes may create broken links.
- Reusable applications become difficult to maintain.
- URL namespaces cannot be used effectively.
URL reversing improves maintainability by generating the current URL from its pattern name and parameters.
What is re_path() in Django? Explain how regular expressions can be used in URL patterns.
re_path() maps URLs using a Python regular expression. It is useful when a route requires matching rules that are more complex than the built-in path converters.
Example:
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^archive/(?P<year>[0-9]{4})/$', views.archive, name='archive'),
]View:
def archive(request, year):
# year is the captured four-digit value
passExplanation:
^marks the beginning of the route.archive/matches literal text.(?P<year>[0-9]{4})captures exactly four digits under the nameyear.$marks the end of the route.
Named groups are preferred because Django passes them as keyword arguments. re_path() should be used only when path() and its converters cannot clearly express the required pattern.
Construct and explain a regular-expression URL pattern that accepts a four-digit year and a two-digit month.
A suitable URL pattern is:
from django.urls import re_path
from . import views
urlpatterns = [
re_path(
r'^reports/(?P<year>[0-9]{4})/(?P<month>0[1-9]|1[0-2])/$',
views.monthly_report,
name='monthly_report'
),
]The corresponding view is:
def monthly_report(request, year, month):
# Generate the report for the captured year and month
passPattern explanation:
^reports/requires the URL to begin withreports/.(?P<year>[0-9]{4})captures exactly four digits asyear.(?P<month>0[1-9]|1[0-2])accepts months from01to12./separates the year and month.$ensures that no additional characters follow.
Valid examples include /reports/2025/01/ and /reports/2024/12/. A value such as /reports/2025/15/ does not match.
Explain the URL resolution process followed by Django when a client requests a page.
Django resolves a request through the following sequence:
- A client sends an HTTP request to the server.
- Django creates an
HttpRequestobject. - Django determines the root URL configuration from the project settings.
- It checks
urlpatternsfrom top to bottom. - If a pattern uses
include(), Django removes the matched prefix and checks the included URL configuration. - Path parameters or regular-expression groups are captured.
- Django imports and calls the matched view with the request and captured arguments.
- The view performs its logic and returns an
HttpResponseobject. - Middleware processes the response as it returns through the stack.
- Django sends the final HTTP response to the client.
Only the first matching URL pattern is used. Therefore, pattern order is important, particularly when both general and specific routes exist.
Describe how a Django view can process both GET and POST requests for a form.
A view can inspect request.method to decide whether to display a form or process submitted data.
from django.shortcuts import render, redirectdef feedback(request):
if request.method == 'POST':
message = request.POST.get('message', '').strip()
if not message:
return render(
request,
'feedback.html',
{'error': 'Message is required.'},
status=400
)
# Save or process the message
return redirect('feedback_success')
return render(request, 'feedback.html')
The logic is:
- For GET, display an empty form.
- For POST, read values from
request.POST. - Validate the submitted values.
- Re-render the form with errors if validation fails.
- Process valid data and redirect to another URL.
Redirecting after successful processing follows the Post/Redirect/Get pattern and helps prevent duplicate submissions when the page is refreshed.
Explain how 404 Not Found errors can be handled in Django views.
A 404 Not Found response indicates that the requested resource does not exist.
A view can explicitly raise Http404:
from django.http import Http404
from .models import Bookdef book_detail(request, book_id):
try:
book = Book.objects.get(id=book_id)
except Book.DoesNotExist:
raise Http404('Book not found')
Django also provides the get_object_or_404() shortcut:
from django.shortcuts import get_object_or_404, render
from .models import Bookdef book_detail(request, book_id):
book = get_object_or_404(Book, id=book_id)
return render(request, 'book_detail.html', {'book': book})
If the object does not exist, get_object_or_404() raises Http404. Django then displays its standard 404 page or a custom 404.html template when DEBUG is False.
Discuss custom error handlers for HTTP 400, 403, 404, and 500 errors in Django.
Django allows a project to define custom handlers for common HTTP errors. The handlers are assigned in the root URL configuration.
handler400 = 'core.views.bad_request'
handler403 = 'core.views.permission_denied'
handler404 = 'core.views.page_not_found'
handler500 = 'core.views.server_error'Example 404 handler:
from django.shortcuts import renderdef page_not_found(request, exception):
return render(request, 'errors/404.html', status=404)
Their purposes are:
- 400 Bad Request: The request is malformed or invalid.
- 403 Forbidden: The client is authenticated or identified but lacks permission.
- 404 Not Found: The requested page or resource does not exist.
- 500 Internal Server Error: An unexpected server-side exception occurred.
Important points:
- Custom handlers are usually tested with
DEBUG = False. - Each response must use the correct status code.
- The 400, 403, and 404 handlers normally accept
requestandexception. - The 500 handler normally accepts only
request. - Error pages should avoid exposing confidential debugging information.
Explain best practices for creating views, designing URLs, and handling errors in a Django application.
Important best practices include:
- Keep views focused: A view should handle request and response logic without becoming excessively large.
- Use meaningful URLs: Prefer
/products/15/to unclear routes such as/getp?id=15. - Use named URL patterns: Generate links with
reverse()or the{% url %}template tag. - Organize URLs by application: Use
include()to create modular URL configurations. - Prefer
path()for common routes: Usere_path()only for genuinely complex matching. - Validate all input: Never assume URL, GET, or POST parameters are safe or correctly formatted.
- Use appropriate HTTP methods: GET should retrieve data, while POST should create or modify data.
- Return correct status codes: For example, use 400 for bad input, 403 for forbidden access, and 404 for missing resources.
- Use shortcuts appropriately:
render(),redirect(), andget_object_or_404()reduce repetitive code. - Protect POST forms: Use CSRF protection and permission checks.
- Avoid broad exception handling: Catch specific exceptions and allow unexpected failures to be logged.
- Hide technical details in production: Set
DEBUG = Falseand provide user-friendly custom error pages.
These practices make Django applications secure, readable, testable, and maintainable.
Define a view in Django. Explain its role in processing a web request.
A view is a Python function or class that receives an HTTP request and returns an HTTP response.
The role of a view includes:
- Receiving an
HttpRequestobject from Django. - Executing application logic, such as retrieving data from a database.
- Processing form data or URL parameters.
- Selecting and rendering an HTML template when required.
- Returning an
HttpResponse, redirect, JSON response, or error response.
Example:
from django.http import HttpResponse
def home(request):
return HttpResponse('Welcome to the home page')When a URL is mapped to home, Django calls this function and sends the returned response to the browser.
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 →