Unit 6: Cookies and Sessions, users and authentication - Practice Quiz
1 Which method is used to create a cookie in a Django HTTP response?
request.add_cookie()
response.add_cookie()
response.set_cookie()
request.set_cookie()
2 Which attribute provides access to cookies received in a Django request?
request.HEADERS
request.COOKIES
request.MESSAGES
request.SESSIONS
3 Which method removes a cookie from a Django response?
request.clear_cookie()
response.remove_cookie()
response.delete_cookie()
request.delete_cookie()
4 How is a value normally stored in a Django session?
response.session["key"] = value
request.cookies["key"] = value
request.session["key"] = value
response.cookies["key"] = value
5 Which method removes all data from the current Django session and deletes its session key?
request.session.create()
request.session.flush()
request.session.cycle_key()
request.session.save()
6 Which built-in Django model is commonly used to represent a user?
Member
Profile
User
Account
7 Which manager method creates a regular Django user while correctly processing the password?
User.objects.save_user()
User.objects.create_user()
User.objects.add_user()
User.objects.create_admin()
8 Which command creates a Django superuser from the command line?
python manage.py addsuperuser
python manage.py createadmin
python manage.py createsuperuser
python manage.py registeradmin
9 Which method should be used to change a user's password securely?
user.change_password()
user.set_password()
user.create_password()
user.save_password()
10 Which user attribute indicates whether a Django user can access the admin site?
is_logged_in
is_staff
is_active
is_private
11 Which URL configuration includes Django's built-in authentication routes?
include("django.accounts.auth.urls")
include("django.auth.login.urls")
include("django.contrib.user.urls")
include("django.contrib.auth.urls")
12 What is the default URL name for Django's built-in login route?
authenticate
user-login
signin
login
13 What is the default URL name for Django's built-in logout route?
user-logout
signout
logout
disconnect
14 Which class-based view provides Django's built-in login behavior?
SignInView
UserLoginView
AuthenticationView
LoginView
15 Which class-based view provides Django's built-in logout behavior?
SignOutView
DisconnectView
LogoutView
UserLogoutView
16 Which Django function checks a username and password and returns a user when the credentials are valid?
check_login()
authorize()
authenticate()
validate_user()
17 Which function attaches an authenticated user to the current Django session?
authorize(request, user)
connect(request, user)
signin(request, user)
login(request, user)
18 Which function logs the current user out in a Django view?
disconnect(request)
end_login(request)
signout(request)
logout(request)
19 Which decorator restricts a function-based Django view to authenticated users?
@signed_in_only
@authentication_only
@user_required
@login_required
20 Which expression checks whether the current user is authenticated?
request.session.is_authenticated
request.auth.user_exists
request.user.is_authenticated
request.user.is_logged_in
21 A view must store a visitor's preferred theme in a cookie before returning a response. Which implementation is correct?
response.COOKIES.save("theme", "dark") after returning the response.
request.set_cookie("theme", "dark") and return an HttpResponse.
request.COOKIES["theme"] = "dark" before rendering the template.
response.set_cookie("theme", "dark"), and return the response.
22
A cookie named language may not exist in every request. Which expression safely returns "en" when the cookie is missing?
request.cookies.language(default="en")
request.get_cookie("language") or "en"
request.COOKIES.get("language", "en")
request.COOKIES["language", "en"]
23 A shopping-cart view needs to store a product ID in the current user's Django session. Which statement should the view use?
response.session["product_id"] = product_id
request.COOKIES["product_id"] = product_id
request.session["product_id"] = product_id
settings.SESSION["product_id"] = product_id
24 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?
settings.SESSION_COOKIE_AGE = 1209600 inside the view, which immediately modifies only the active user's session and leaves all other sessions unchanged.
response.set_session_age(1209600)
request.session.set_expiry(1209600)
request.session.set_timeout(1209600)
25 A logout-related view must remove all session data and invalidate the current session key. Which method is most appropriate?
request.session.set_expiry(0)
request.session.flush()
request.session.clear()
request.session.delete()
26 A registration view must create a user while ensuring that the password is securely hashed. Which approach is correct?
User.objects.create_user(username="mina", password="secret123")
User(username="mina", password=hash("secret123")).save()
User.objects.create(username="mina", password="secret123")
User.objects.get_or_create(username="mina", password="secret123")
27 An administrator has retrieved a user object and wants to replace its password. Which code correctly updates the stored password?
user.password = "newpass"; user.save()
user.password.set("newpass"); user.save()
user.update_password("newpass"); user.commit()
user.set_password("newpass"); user.save()
28 A user should be allowed to access the Django administration site but should receive only explicitly assigned permissions. Which flag should normally be enabled?
is_authenticated
is_superuser
is_staff
is_active
29 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?
UserCreationForm
PasswordChangeForm
AuthenticationForm
ModelForm, because every model form automatically adds two password fields, compares them, hashes the result, and creates the authenticated session.
30
A user has been assigned the blog.change_post permission. Which expression checks that permission using Django's authorization API?
user.can_change("blog.Post")
user.is_allowed("blog", "change", "post")
user.has_perm("blog.change_post")
user.permissions.contains("change_post")
31
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?
path("accounts/", include("django.contrib.auth.urls"))
path("accounts/", include("django.contrib.admin.urls"))
path("accounts/", include("django.contrib.auth.models"))
path("accounts/", auth_views.all_urls())
32
After including django.contrib.auth.urls under /accounts/, which URL is used by the default named login route?
/accounts/authenticate/
/accounts/login/
/accounts/signin/
/accounts/user/login/
33
Django's built-in LoginView is used without specifying template_name. Which template path does it look for by default?
auth/login_form.html
templates/login.html
registration/login.html
accounts/login.html
34
A project should redirect users to /dashboard/ after login when no next parameter is provided. Which setting should be configured?
AUTH_SUCCESS_URL = "/dashboard/", which also overrides permission checks and changes the destination of every logout request.
LOGOUT_REDIRECT_URL = "/dashboard/"
LOGIN_REDIRECT_URL = "/dashboard/"
LOGIN_URL = "/dashboard/"
35 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?
{% url 'logout' %}
{% route 'logout' %}
{% auth_url 'logout' %}
{% reverse '/accounts/logout/' %}
36 A function-based view must be accessible only to authenticated users. Which implementation follows Django's standard approach?
@login_required above the view function.
request.session["logged_in"] in every request.
@authenticated_user above the view function.
request.user.is_authenticated = True at the beginning of the view.
37 A login view has received a username and password. What is the correct sequence for establishing an authenticated session?
user.password, then store the username in a cookie that serves as Django's authenticated session.
create_user(), then assign the result to request.user.
authenticate(), verify the result, then call login().
login() first, then call authenticate().
38 A view should display a personalized dashboard only when the current request belongs to an authenticated user. Which condition is appropriate?
if request.user.is_logged_in():
if request.user.is_authenticated:
if request.user.password is not None:
if request.session.is_authenticated:
39
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?
@login_required("inventory.delete_product", forbidden=True)
@require_permission("delete_product", app="inventory")
@permission_required("inventory.delete_product", raise_exception=True)
@user_passes_test("inventory.delete_product", status=403)
40 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?
request.session.clear() followed by authenticate(request)
request.user = AnonymousUser() followed by request.session.save()
logout(request) followed by redirect("home")
request.user.delete() followed by redirect("home")
41
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?
theme cookie and the body OK
theme cookie and the body Done
theme cookie and the body OK
theme cookie and the body Done
42
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?
BadSignature exception
None after removing the cookie
43
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?
44
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?
request.session.cycle_key()
request.session.accessed = False
request.session.modified = True
request.session.set_expiry(None)
45 Which session operation is appropriate after a privilege change when the application must issue a new session key while preserving the current session data?
request.session.flush()
request.session.clear()
request.session.clear_expired()
request.session.cycle_key()
46
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?
SESSION_COOKIE_AGE is changed
47
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?
authenticate()
48
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?
models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
models.ForeignKey(User, on_delete=models.CASCADE)
models.ForeignKey("auth.User", on_delete=models.CASCADE)
49
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?
50
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?
set_password() to invalidate permission state
force_update=True
51
A password passes through User.objects.create_user() but violates a validator listed in AUTH_PASSWORD_VALIDATORS. Why can this occur?
create_user() hashes passwords but does not automatically run validators
create_user() runs validators only when the user is a superuser
52
A project adds path("accounts/", include("django.contrib.auth.urls")) to its root URL configuration. Which statement is correct?
53
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?
/collect locally
54
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?
55
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?
/dashboard/; logout goes to /signed-out/
/signed-out/; logout goes to /dashboard/
/signed-out/
/dashboard/
56
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?
next parameter
next parameter
next parameter
57
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?
class EditView(UpdateView, View, LoginRequiredMixin):
class EditView(UpdateView, LoginRequiredMixin):
class EditView(LoginRequiredMixin, UpdateView):
class EditView(View, UpdateView, LoginRequiredMixin):
58
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?
login()
login()
request.user before calling login()
59
A view stores shopping-cart data in request.session and then calls django.contrib.auth.logout(request). What happens to that session data?
SESSION_COOKIE_AGE expires
60
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?
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 →