Unit 6: Cookies and Sessions, users and authentication - Subjective Questions
INT253 — Web Development In Python Using Django • Practice Questions with Detailed Answers
20 questions
Explain the concept of cookies in Django. Describe how cookies are created, accessed, modified, and deleted in a Django application.
Cookies are small pieces of data stored in a user's browser. Django allows a server to send cookies in an HTTP response and read them from subsequent requests.
- A cookie can be created using
response.set_cookie("key", "value"). - Cookies can be accessed through
request.COOKIES.get("key"). - A cookie can be modified by setting the same key with a new value.
- A cookie can be deleted using
response.delete_cookie("key"). - Cookie options such as
max_age,expires,secure, andhttponlycan control its behavior.
Example:
from django.http import HttpResponse
def set_preference(request):
response = HttpResponse("Preference saved")
response.set_cookie("theme", "dark", max_age=3600)
return responsedef read_preference(request):
theme = request.COOKIES.get("theme", "light")
return HttpResponse(f"Selected theme: {theme}")
Cookies should not be used to store sensitive information directly because users can inspect them. Sensitive data should be protected with appropriate security settings or stored on the server.
Describe Django sessions and explain how session data is stored and retrieved in views.
A session provides a way to store information about a user across multiple HTTP requests. Since HTTP is stateless, sessions allow Django to remember information such as login state, shopping-cart data, or user preferences.
- Session data is accessed through
request.session. - Values can be assigned using dictionary-style syntax.
- Values can be retrieved using
request.session.get(). - Data can be removed using
delorrequest.session.pop(). - The session is usually identified by a session cookie, while the actual data is stored on the server by default.
Example:
from django.http import HttpResponse
def add_item(request):
request.session["item_count"] = request.session.get("item_count", 0) + 1
return HttpResponse("Item added")def show_item_count(request):
count = request.session.get("item_count", 0)
return HttpResponse(f"Items: {count}")
For sessions to work, django.contrib.sessions must be installed, SessionMiddleware must be included in MIDDLEWARE, and the session database table must normally be created using migrations.
Compare cookies and sessions in Django with respect to storage, security, capacity, lifetime, and typical uses.
| Feature | Cookies | Sessions |
|---|---|---|
| Storage | Stored in the user's browser | Usually stored on the server |
| Identifier | The cookie contains the data or an identifier | The browser usually stores a session identifier |
| Security | More exposed because users can inspect and modify them | Server-side data is less directly exposed |
| Capacity | Limited by browser cookie limits | Depends on the configured session backend |
| Lifetime | Can be temporary or persistent | Can expire when the browser closes or after a configured period |
| Typical uses | Preferences, language selection, tracking identifiers | Authentication state, carts, and temporary user data |
Cookies are appropriate for small, non-sensitive client-side values. Sessions are better for server-side state and sensitive information. Django authentication uses sessions to maintain the user's authenticated state between requests.
Explain how to configure sessions in a Django project and mention the important settings and middleware involved.
Django sessions require both configuration and middleware support.
- Add
django.contrib.sessionstoINSTALLED_APPS. - Include
django.contrib.sessions.middleware.SessionMiddlewareinMIDDLEWARE. - Run
python manage.py migrateto create the required database tables when using the database session backend. - Configure the session engine with
SESSION_ENGINEif a backend other than the default is required. - Configure the session lifetime using
SESSION_COOKIE_AGE. - Use
SESSION_EXPIRE_AT_BROWSER_CLOSEwhen sessions should expire after the browser closes. - Use secure cookie settings such as
SESSION_COOKIE_SECURE,SESSION_COOKIE_HTTPONLY, andSESSION_COOKIE_SAMESITEwhere appropriate.
The middleware attaches a session object to every request. Views can then read and update session data through request.session. Session configuration should be reviewed together with HTTPS and security requirements.
Write and explain a Django view that uses a session to implement a simple shopping cart.
A shopping cart can be represented as a list or dictionary stored in the user's session. The session makes the cart available across multiple requests without requiring an immediate database model.
from django.http import JsonResponse
def add_to_cart(request, product_id):
cart = request.session.get("cart", {})
product_key = str(product_id)
cart[product_key] = cart.get(product_key, 0) + 1
request.session["cart"] = cart
request.session.modified = True
return JsonResponse({"cart": cart})def view_cart(request):
cart = request.session.get("cart", {})
return JsonResponse({"cart": cart})
The product identifier is converted to a string because session data is commonly serialized as JSON-compatible data. request.session.modified = True is useful when nested data is changed in place and Django may not automatically detect the modification. For large or permanent carts, a database-backed design associated with a user account is generally more suitable.
Explain the Django User model and describe how a new user can be created programmatically.
Django provides a built-in User model through django.contrib.auth.models.User. It includes common fields and behavior for authentication, such as username, password, email address, active status, staff status, and superuser status.
A user can be created as follows:
from django.contrib.auth.models import User
user = User.objects.create_user(
username="student1",
email="student1@example.com",
password="strong-password"
)Important points:
- Use
create_user()instead of assigning a password directly. - Django hashes the password before storing it.
is_activecontrols whether the account can authenticate.is_staffcontrols access to staff features such as the admin site.is_superusergrants all permissions.- Usernames must satisfy the configured uniqueness and validation rules.
Passwords must never be stored as plain text.
Describe the process of managing users in Django, including updating, deactivating, deleting, and checking user account properties.
Users can be managed through the ORM, Django forms, the admin interface, or custom views.
- Retrieve: Use
User.objects.get()orUser.objects.filter(). - Update: Change fields and call
save(). - Change password: Use
user.set_password(new_password)and then callsave(). - Deactivate: Set
user.is_active = Falseand save the user. - Delete: Call
user.delete(), although deactivation is often safer for auditability. - Check privileges: Use
user.is_staff,user.is_superuser, and permission methods. - Check authentication: Use
user.is_authenticatedin views or templates.
Example:
user = User.objects.get(username="student1")
user.email = "new-address@example.com"
user.set_password("new-password")
user.save()User management views should validate input, restrict access to authorized administrators, and avoid exposing account details to unauthorized users.
Explain the difference between authentication and authorization in Django.
Authentication verifies who a user is. In Django, it commonly involves submitting credentials and using authenticate() to check them.
Authorization determines what an authenticated user is allowed to do. Django supports authorization through:
- Model permissions such as add, change, delete, and view.
- Groups containing collections of permissions.
- The
is_staffandis_superuserflags. - Custom permissions.
- View-level checks such as
login_requiredand permission decorators.
For example, a successful login authenticates a user, but it does not automatically grant permission to edit every record. The application must separately check whether that user has the required permission. Keeping these concepts separate improves security and makes access rules easier to maintain.
Explain the purpose and usage of Django's authenticate() function.
The authenticate() function checks supplied credentials against the configured authentication backends. It returns a user object when the credentials are valid and returns None when authentication fails.
Example:
from django.contrib.auth import authenticate
user = authenticate(username="student1", password="strong-password")
if user is not None:
message = "Credentials are valid"
else:
message = "Invalid credentials"Important details:
- It does not itself create a login session.
- The returned user should be passed to
login()to persist authentication. - Authentication backends determine which credentials and user sources are supported.
- A user marked inactive may not authenticate, depending on the backend.
- Error messages should not reveal whether only the username or only the password was incorrect.
A complete login workflow generally calls authenticate() first and login() after successful authentication.
Describe how the Django login() and logout() functions work and explain their effect on the session.
The login() function associates an authenticated user with the current session. This allows Django to recognize the user on later requests.
from django.contrib.auth import login, logout
login(request, user)After this call, request.user represents the logged-in user for subsequent requests, provided the authentication middleware is enabled.
The logout() function removes the authenticated user's information from the current session:
logout(request)A typical logout view is:
from django.contrib.auth import logout
from django.shortcuts import redirect
def sign_out(request):
logout(request)
return redirect("login")Logging out helps prevent unauthorized use of a session on shared devices. Applications should ensure that logout URLs are protected against unsafe request patterns and should use POST requests where appropriate for security-sensitive workflows.
Explain how to configure login and logout URLs in Django using built-in authentication views.
Django provides built-in class-based authentication views such as LoginView and LogoutView. They reduce the amount of authentication code required in a project.
Example URL configuration:
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path("login/", auth_views.LoginView.as_view(template_name="registration/login.html"), name="login"),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
]Relevant settings include:
LOGIN_REDIRECT_URL = "/dashboard/"
LOGOUT_REDIRECT_URL = "/"The login template normally contains a form that submits to the login URL and includes {% csrf_token %}. The application should also configure LOGIN_URL for redirecting unauthenticated users. URL names are preferable to hard-coded paths because they support maintainable reverse URL resolution.
Write a custom Django login view using authenticate() and login(), and explain each step.
A custom login view is useful when an application needs special validation or custom behavior.
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirectdef sign_in(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("dashboard")
return render(request, "login.html", {"error": "Invalid login details"})
return render(request, "login.html")
The process is:
- Display the login form for a GET request.
- Read submitted credentials for a POST request.
- Call
authenticate()to validate them. - Call
login()if a valid user is returned. - Redirect the user after successful login.
- Redisplay a safe error message after failure.
The form should include CSRF protection, and redirect targets should be validated to avoid open-redirect vulnerabilities.
Explain how the @login_required decorator is used to protect Django views.
The @login_required decorator restricts access to a view to authenticated users. If an anonymous user requests the protected view, Django redirects the user to the configured login page.
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@login_required
def dashboard(request):
return HttpResponse(f"Welcome, {request.user.username}")The redirect commonly includes a next query parameter containing the original destination. After successful login, the user can be returned to that destination.
Configuration example:
LOGIN_URL = "/login/"
LOGIN_REDIRECT_URL = "/dashboard/"The decorator performs an authentication check, but it does not determine whether the user has a particular permission. Permission checks must be added separately when required.
Describe how to use request.user in Django views and explain the difference between an anonymous user and an authenticated user.
request.user is supplied by Django's authentication middleware. It represents the current user associated with the request.
- For a logged-in user,
request.useris a User instance. - For a visitor who is not logged in, it is an
AnonymousUserinstance. - The property
request.user.is_authenticatedindicates whether the user is authenticated. - User fields such as
username,email, andis_staffcan be accessed after authentication checks.
Example:
from django.http import HttpResponse
def profile(request):
if request.user.is_authenticated:
return HttpResponse(f"Profile: {request.user.username}")
return HttpResponse("Please log in")The view should check authentication before accessing user-specific data. Authentication middleware must appear after session middleware in the middleware configuration.
Explain how to restrict a Django view using a user's permissions or group membership.
Django supports authorization through permissions and groups. A user can be assigned permissions directly or receive them through a group.
A function-based view can use permission_required:
from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required("app.change_record", raise_exception=True)
def edit_record(request):
return render(request, "edit_record.html")Permission checks can also be performed manually:
if request.user.has_perm("app.change_record"):
# Permit the operation
passGroups simplify administration because permissions can be assigned to a role rather than to each user individually. Authentication should be checked before authorization. A user being logged in does not imply that the user has permission to perform every operation.
Describe the complete request flow when an unauthenticated user accesses a protected Django view.
The request flow for a protected view is as follows:
- The browser sends a request to the protected URL.
SessionMiddlewareloads the session associated with the session cookie.AuthenticationMiddlewareuses session information to setrequest.user.- The
login_requireddecorator checksrequest.user.is_authenticated. - Because the user is anonymous, the decorator redirects the request to
LOGIN_URL. - The redirect normally includes a
nextparameter containing the original URL. - The user submits valid credentials through the login form.
- The application calls
authenticate()and thenlogin(). - Django stores authentication information in the session.
- The user is redirected to the original URL or the configured login destination.
This flow depends on correctly configured sessions, authentication middleware, URL patterns, and login settings.
Explain how cookies and sessions should be secured in a Django application.
Cookie and session security is important because authentication state is commonly represented through a session cookie.
Recommended practices include:
- Use HTTPS in production.
- Set
SESSION_COOKIE_SECURE = Trueso the cookie is sent only over HTTPS. - Set
SESSION_COOKIE_HTTPONLY = Trueto reduce access from client-side scripts. - Configure
SESSION_COOKIE_SAMESITEto reduce cross-site request risks. - Keep CSRF protection enabled for state-changing requests.
- Do not store passwords or sensitive secrets in cookies.
- Use short and appropriate session lifetimes.
- Rotate or invalidate sessions after important security events.
- Use strong secret-key management and never expose
SECRET_KEY. - Avoid putting untrusted data into session-dependent operations without validation.
These settings should be selected according to the application's deployment environment and threat model.
Distinguish between session-based login and storing login information manually in a cookie.
In session-based login, Django stores authentication information in the server-side session and sends the browser a session identifier. The server validates the identifier and reconstructs the authenticated user for each request.
In manual cookie-based login, an application stores user identity or authentication data directly in a browser cookie. This approach is risky because the cookie may be inspected, modified, stolen, or replayed.
Session-based authentication is preferred because:
- Django provides established login and logout functions.
- Passwords and sensitive authentication details are not stored directly in the cookie.
- Sessions can be invalidated on the server.
- Middleware automatically populates
request.user. - Built-in security features and authentication backends can be used.
A cookie may still identify the session, but it should not be treated as a trusted storage location for user credentials.
Explain the role of CSRF protection in Django login and logout forms.
Cross-Site Request Forgery (CSRF) occurs when a malicious site causes a user's browser to submit an unwanted request to another site where the user is authenticated. Django provides CSRF protection for unsafe HTTP methods such as POST, PUT, PATCH, and DELETE.
A login form should include the CSRF token:
<form method="post">
{% csrf_token %}
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Log in</button>
</form>The token is checked by Django's CSRF middleware. If it is missing or invalid, Django rejects the request. State-changing actions should use POST rather than GET. In particular, applications should avoid designing logout as an unsafe GET action when CSRF protection is required.
Describe the purpose of LoginView and LogoutView and compare them with custom authentication views.
LoginView and LogoutView are reusable class-based views supplied by Django.
LoginViewdisplays a login form, validates submitted credentials, logs in the user, and redirects after success.LogoutViewlogs out the current user and redirects to a configured destination.- Templates, redirect URLs, and form behavior can be customized through settings and class attributes.
Built-in views are suitable for standard authentication workflows and reduce duplicated code. Custom views are useful when an application requires additional behavior, such as multi-step authentication, custom account checks, audit logging, or integration with an external service.
Regardless of the approach, the application must configure URLs, templates, CSRF protection, session middleware, and safe redirect behavior.
Explain the concept of cookies in Django. Describe how cookies are created, accessed, modified, and deleted in a Django application.
Cookies are small pieces of data stored in a user's browser. Django allows a server to send cookies in an HTTP response and read them from subsequent requests.
- A cookie can be created using
response.set_cookie("key", "value"). - Cookies can be accessed through
request.COOKIES.get("key"). - A cookie can be modified by setting the same key with a new value.
- A cookie can be deleted using
response.delete_cookie("key"). - Cookie options such as
max_age,expires,secure, andhttponlycan control its behavior.
Example:
from django.http import HttpResponse
def set_preference(request):
response = HttpResponse("Preference saved")
response.set_cookie("theme", "dark", max_age=3600)
return responsedef read_preference(request):
theme = request.COOKIES.get("theme", "light")
return HttpResponse(f"Selected theme: {theme}")
Cookies should not be used to store sensitive information directly because users can inspect them. Sensitive data should be protected with appropriate security settings or stored on the server.
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 →