Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
You're offline
Unit 6 MCQsCookies and Sessions, users and authentication
Django exposes the current session through request.session, which behaves like a mutable dictionary.
Question 24 of 60 · Creating Cookies and sessions in Django · Medium
A user selects "Remember me" during login, and the application should keep the session for two weeks. Which call applies this expiry to the current session?
Not quite. Try another option.
Answer: request.session.set_expiry(1209600)
set_expiry() accepts a number of seconds for the current session. Two weeks equals 1,209,600 seconds.
Question 25 of 60 · Creating Cookies and sessions in Django · Medium
A logout-related view must remove all session data and invalidate the current session key. Which method is most appropriate?
Not quite. Try another option.
Answer: request.session.flush()
flush() deletes the current session data and its session key, then creates a fresh session key when needed.
Question 26 of 60 · Creating and Managing Users in Django · Medium
A registration view must create a user while ensuring that the password is securely hashed. Which approach is correct?
create_user() normalizes user data and hashes the supplied password before saving the user.
Question 27 of 60 · Creating and Managing Users in Django · Medium
An administrator has retrieved a user object and wants to replace its password. Which code correctly updates the stored password?
Not quite. Try another option.
Answer: user.set_password("newpass"); user.save()
set_password() hashes the new password. Calling save() then stores the resulting password hash in the database.
Question 28 of 60 · Creating and Managing Users in Django · Medium
A user should be allowed to access the Django administration site but should receive only explicitly assigned permissions. Which flag should normally be enabled?
Not quite. Try another option.
Answer: is_staff
is_staff allows access to the admin site. Unlike is_superuser, it does not automatically grant every permission.
Question 29 of 60 · Creating and Managing Users in Django · Medium
A registration form should validate that two password entries match and should save the password securely. Which built-in form is designed for this task?
Not quite. Try another option.
Answer: UserCreationForm
UserCreationForm provides username and password confirmation fields, validates matching passwords, and saves the password securely.
Question 30 of 60 · Creating and Managing Users in Django · Medium
A user has been assigned the blog.change_post permission. Which expression checks that permission using Django's authorization API?
Not quite. Try another option.
Answer: user.has_perm("blog.change_post")
has_perm() expects a permission string in the form app_label.permission_codename.
Question 31 of 60 · Login and Logout URLs in Django · Medium
A project wants to use Django's built-in login, logout, and password-management URL patterns under /accounts/. Which project-level URL pattern is appropriate?
Including django.contrib.auth.urls adds Django's built-in authentication routes beneath the chosen prefix.
Question 32 of 60 · Login and Logout URLs in Django · Medium
After including django.contrib.auth.urls under /accounts/, which URL is used by the default named login route?
Not quite. Try another option.
Answer: /accounts/login/
The included authentication URL configuration provides the named login route at login/, producing /accounts/login/.
Question 33 of 60 · Login and Logout URLs in Django · Medium
Django's built-in LoginView is used without specifying template_name. Which template path does it look for by default?
Not quite. Try another option.
Answer: registration/login.html
By default, Django's LoginView renders the template registration/login.html.
Question 34 of 60 · Login and Logout URLs in Django · Medium
A project should redirect users to /dashboard/ after login when no next parameter is provided. Which setting should be configured?
Not quite. Try another option.
Answer: LOGIN_REDIRECT_URL = "/dashboard/"
LOGIN_REDIRECT_URL defines the fallback destination after a successful login when another redirect target is not supplied.
Question 35 of 60 · Login and Logout URLs in Django · Medium
A template should generate the logout URL without hard-coding its path. Which template tag should be used when Django's authentication URLs are included?
Not quite. Try another option.
Answer: {% url 'logout' %}
Django registers the built-in logout route with the name logout, and the url template tag reverses that name.
Question 36 of 60 · Using Django Login in Views · Medium
A function-based view must be accessible only to authenticated users. Which implementation follows Django's standard approach?
Not quite. Try another option.
Answer: Apply @login_required above the view function.
@login_required redirects anonymous users to the configured login page and allows authenticated users to access the view.
Question 37 of 60 · Using Django Login in Views · Medium
A login view has received a username and password. What is the correct sequence for establishing an authenticated session?
Not quite. Try another option.
Answer: Call authenticate(), verify the result, then call login().
authenticate() validates the credentials and returns a user or None. login() then stores the authenticated user's identity in the session.
Question 38 of 60 · Using Django Login in Views · Medium
A view should display a personalized dashboard only when the current request belongs to an authenticated user. Which condition is appropriate?
Not quite. Try another option.
Answer: if request.user.is_authenticated:
request.user.is_authenticated distinguishes authenticated users from AnonymousUser objects.
Question 39 of 60 · Using Django Login in Views · Medium
A function-based view should require the inventory.delete_product permission and raise an HTTP 403 response when an authenticated user lacks it. Which decorator is appropriate?
permission_required() checks the specified permission, and raise_exception=True causes unauthorized authenticated users to receive HTTP 403.
Question 40 of 60 · Using Django Login in Views · Medium
A custom logout view needs to remove the authenticated user's identity from the session before redirecting to the home page. Which code performs the logout correctly?
Not quite. Try another option.
Answer: logout(request) followed by redirect("home")
Django's logout(request) removes authentication data from the session. The view can then return a redirect to the home page.
Question 41 of 60 · Creating Cookies and sessions in Django · Hard
A view executes response = HttpResponse("OK"), calls response.set_cookie("theme", "dark"), but finally returns a newly created HttpResponse("Done"). What will the client receive?
Not quite. Try another option.
Answer: No theme cookie and the body Done
set_cookie() modifies the specific response object. Because a different response is returned, its Set-Cookie header is not sent.
Question 42 of 60 · Creating Cookies and sessions in Django · Hard
A cookie created with response.set_signed_cookie("role", "editor", salt="access") is later modified by the client. What happens when the server calls request.get_signed_cookie("role", salt="access") without a default value?
Not quite. Try another option.
Answer: It raises Django's BadSignature exception
Signed cookies provide tamper detection. A changed value no longer matches its signature, so Django raises BadSignature.
Question 43 of 60 · Creating Cookies and sessions in Django · Hard
A cookie was set with path="/store/" and domain="example.com". A later call to delete_cookie("cart") uses the defaults for both attributes. Why might the browser retain the cookie?
Not quite. Try another option.
Answer: The deletion must use the matching path and domain
Browsers identify cookies using attributes including name, path, and domain. The deletion response must target the same cookie scope.
Question 44 of 60 · Creating Cookies and sessions in Django · Hard
Given request.session["prefs"] = {"theme": "light"}, a later request executes request.session["prefs"]["theme"] = "dark". Under Django's default save-on-modification behavior, what is required to reliably persist this nested change?
Not quite. Try another option.
Answer: Set request.session.modified = True
Django may not detect mutation inside a nested object because the top-level session mapping was not reassigned. Marking the session modified forces a save.
Question 45 of 60 · Creating Cookies and sessions in Django · Hard
Which session operation is appropriate after a privilege change when the application must issue a new session key while preserving the current session data?
Not quite. Try another option.
Answer: Call request.session.cycle_key()
cycle_key() changes the session identifier while retaining its data. flush() removes both the data and the existing session key.
Question 46 of 60 · Creating Cookies and sessions in Django · Hard
A view calls request.session.set_expiry(300). Subsequent requests only read session values and never modify the session. Which expiration behavior should be expected?
Not quite. Try another option.
Answer: The expiry remains based on the last session modification
Reading a Django session does not normally count as activity that refreshes its expiry. Expiration is calculated from the last modification.
Question 47 of 60 · Creating and Managing Users in Django · Hard
A developer creates a user with User.objects.create(username="nina", password="secret"). The row exists, but authentication with secret fails. What is the underlying problem?
Not quite. Try another option.
Answer: The password was stored without Django's password hashing format
Direct assignment stores the raw string rather than a valid encoded password. Use create_user() or set_password() followed by save().
Question 48 of 60 · Creating and Managing Users in Django · Hard
A reusable app needs a foreign key to the project's user model and must support projects that replace Django's default User. Which declaration is appropriate in the model?
settings.AUTH_USER_MODEL provides a lazy model reference suitable for model fields and migrations. get_user_model() is intended for runtime access.
Question 49 of 60 · Creating and Managing Users in Django · Hard
A custom user manager implements create_superuser() but permits is_staff=False or is_superuser=False when explicitly supplied. What should a robust implementation do?
Not quite. Try another option.
Answer: Reject either false value with an explicit error
A superuser must have both is_staff=True and is_superuser=True. A custom manager should enforce these invariants and reject conflicting values.
Question 50 of 60 · Creating and Managing Users in Django · Hard
A long-lived User instance has already been checked with has_perm(). Its group permissions are then changed in the database, but another check on the same instance returns the old result. What is the safest correction?
Not quite. Try another option.
Answer: Re-fetch the user instance before checking permissions
Django authentication backends cache permissions on the user object. Re-fetching creates an instance without the stale permission caches.
Question 51 of 60 · Creating and Managing Users in Django · Hard
A password passes through User.objects.create_user() but violates a validator listed in AUTH_PASSWORD_VALIDATORS. Why can this occur?
Not quite. Try another option.
Answer: create_user() hashes passwords but does not automatically run validators
Password validation is normally invoked by forms or explicit calls to validate_password(). Model manager methods do not automatically enforce configured validators.
Question 52 of 60 · Login and Logout URLs in Django · Hard
A project adds path("accounts/", include("django.contrib.auth.urls")) to its root URL configuration. Which statement is correct?
Not quite. Try another option.
Answer: It provides named login and logout routes but not the required login template
The included authentication URL configuration supplies routes and views such as login and logout; applications must provide the expected templates.
Question 53 of 60 · Login and Logout URLs in Django · Hard
After successful authentication, LoginView receives next=https://evil.example/collect, while the current host is app.example.com and the external host is not allowed. What should Django do?
Not quite. Try another option.
Answer: Reject the unsafe target and use the configured fallback redirect
LoginView validates redirect targets against allowed hosts and the request scheme. An unsafe next value is ignored in favor of the normal success URL.
Question 54 of 60 · Login and Logout URLs in Django · Hard
LoginView is configured with redirect_authenticated_user=True, and its resolved success URL points back to the same login URL. What protection does Django apply for an already authenticated visitor?
Not quite. Try another option.
Answer: It raises an error rather than following a redirect loop
Django detects when the authenticated-user redirect resolves to the login page itself and raises an error to prevent an infinite loop.
Question 55 of 60 · Login and Logout URLs in Django · Hard
A project sets LOGIN_REDIRECT_URL = "/dashboard/" and LOGOUT_REDIRECT_URL = "/signed-out/". No valid next value or view-level override is supplied. What are the resulting destinations?
Not quite. Try another option.
Answer: Login goes to /dashboard/; logout goes to /signed-out/
LOGIN_REDIRECT_URL controls the default post-login destination, while LOGOUT_REDIRECT_URL controls the default post-logout destination.
Question 56 of 60 · Using Django Login in Views · Hard
An unauthenticated request reaches a view protected by @login_required. The request includes its own query string. Which behavior correctly describes the generated login redirect?
Not quite. Try another option.
Answer: The original path and query string are placed in the next parameter
login_required redirects to the login URL and normally records the complete relative destination, including its query string, in next.
Question 57 of 60 · Using Django Login in Views · Hard
A class-based view inherits from both LoginRequiredMixin and UpdateView. Which inheritance order is required so that the authentication check participates correctly in method dispatch?
Not quite. Try another option.
Answer: class EditView(LoginRequiredMixin, UpdateView):
LoginRequiredMixin should appear before the concrete view class so its dispatch() behavior is reached correctly through Python's method resolution order.
Question 58 of 60 · Using Django Login in Views · Hard
A custom login view retrieves a user directly with get_user_model().objects.get(...) and then calls login(request, user). Multiple authentication backends are configured, and no backend is stored on the user. What is required?
Not quite. Try another option.
Answer: Pass the appropriate dotted backend path to login()
With multiple backends, Django cannot infer which backend should later reload the user. Pass backend=..., or obtain the user through authenticate(), which records it.
Question 59 of 60 · Using Django Login in Views · Hard
A view stores shopping-cart data in request.session and then calls django.contrib.auth.logout(request). What happens to that session data?
Not quite. Try another option.
Answer: It is flushed along with the authenticated session
logout() flushes the session to prevent another user from inheriting data from the previous authenticated session. Preserve needed data explicitly before logout.
Question 60 of 60 · Using Django Login in Views · Hard
An anonymous visitor has cart data in the session. The application authenticates the visitor and calls login(request, user) for a valid user, with no conflicting authenticated-user data in the session. What normally happens?
Not quite. Try another option.
Answer: The session key is cycled while the cart data is retained
During a normal anonymous-to-authenticated transition, Django rotates the session key to reduce session-fixation risk while preserving existing session data.
That's unit 6
Answer a few questions and your score shows up here.
Nearly through. Did unit 6 of INT253 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 6 of INT253 save you a night before the exam?
Then you can help keep it free for the next batch. 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.