Unit 6: Cookies and Sessions, users and authentication - Practice Quiz

INT253 — Web Development In Python Using Django 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which method is used to create a cookie in a Django HTTP response?

Creating Cookies and sessions in Django Easy
A. request.add_cookie()
B. response.add_cookie()
C. response.set_cookie()
D. request.set_cookie()

2 Which attribute provides access to cookies received in a Django request?

Creating Cookies and sessions in Django Easy
A. request.HEADERS
B. request.COOKIES
C. request.MESSAGES
D. request.SESSIONS

3 Which method removes a cookie from a Django response?

Creating Cookies and sessions in Django Easy
A. request.clear_cookie()
B. response.remove_cookie()
C. response.delete_cookie()
D. request.delete_cookie()

4 How is a value normally stored in a Django session?

Creating Cookies and sessions in Django Easy
A. response.session["key"] = value
B. request.cookies["key"] = value
C. request.session["key"] = value
D. response.cookies["key"] = value

5 Which method removes all data from the current Django session and deletes its session key?

Creating Cookies and sessions in Django Easy
A. request.session.create()
B. request.session.flush()
C. request.session.cycle_key()
D. request.session.save()

6 Which built-in Django model is commonly used to represent a user?

Creating and Managing Users in Django Easy
A. Member
B. Profile
C. User
D. Account

7 Which manager method creates a regular Django user while correctly processing the password?

Creating and Managing Users in Django Easy
A. User.objects.save_user()
B. User.objects.create_user()
C. User.objects.add_user()
D. User.objects.create_admin()

8 Which command creates a Django superuser from the command line?

Creating and Managing Users in Django Easy
A. python manage.py addsuperuser
B. python manage.py createadmin
C. python manage.py createsuperuser
D. python manage.py registeradmin

9 Which method should be used to change a user's password securely?

Creating and Managing Users in Django Easy
A. user.change_password()
B. user.set_password()
C. user.create_password()
D. user.save_password()

10 Which user attribute indicates whether a Django user can access the admin site?

Creating and Managing Users in Django Easy
A. is_logged_in
B. is_staff
C. is_active
D. is_private

11 Which URL configuration includes Django's built-in authentication routes?

Login and Logout URLs in Django Easy
A. include("django.accounts.auth.urls")
B. include("django.auth.login.urls")
C. include("django.contrib.user.urls")
D. include("django.contrib.auth.urls")

12 What is the default URL name for Django's built-in login route?

Login and Logout URLs in Django Easy
A. authenticate
B. user-login
C. signin
D. login

13 What is the default URL name for Django's built-in logout route?

Login and Logout URLs in Django Easy
A. user-logout
B. signout
C. logout
D. disconnect

14 Which class-based view provides Django's built-in login behavior?

Login and Logout URLs in Django Easy
A. SignInView
B. UserLoginView
C. AuthenticationView
D. LoginView

15 Which class-based view provides Django's built-in logout behavior?

Login and Logout URLs in Django Easy
A. SignOutView
B. DisconnectView
C. LogoutView
D. UserLogoutView

16 Which Django function checks a username and password and returns a user when the credentials are valid?

Using Django Login in Views Easy
A. check_login()
B. authorize()
C. authenticate()
D. validate_user()

17 Which function attaches an authenticated user to the current Django session?

Using Django Login in Views Easy
A. authorize(request, user)
B. connect(request, user)
C. signin(request, user)
D. login(request, user)

18 Which function logs the current user out in a Django view?

Using Django Login in Views Easy
A. disconnect(request)
B. end_login(request)
C. signout(request)
D. logout(request)

19 Which decorator restricts a function-based Django view to authenticated users?

Using Django Login in Views Easy
A. @signed_in_only
B. @authentication_only
C. @user_required
D. @login_required

20 Which expression checks whether the current user is authenticated?

Using Django Login in Views Easy
A. request.session.is_authenticated
B. request.auth.user_exists
C. request.user.is_authenticated
D. 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?

Creating Cookies and sessions in Django Medium
A. Call response.COOKIES.save("theme", "dark") after returning the response.
B. Call request.set_cookie("theme", "dark") and return an HttpResponse.
C. Assign request.COOKIES["theme"] = "dark" before rendering the template.
D. Create a response, call 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?

Creating Cookies and sessions in Django Medium
A. request.cookies.language(default="en")
B. request.get_cookie("language") or "en"
C. request.COOKIES.get("language", "en")
D. 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?

Creating Cookies and sessions in Django Medium
A. response.session["product_id"] = product_id
B. request.COOKIES["product_id"] = product_id
C. request.session["product_id"] = product_id
D. 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?

Creating Cookies and sessions in Django Medium
A. settings.SESSION_COOKIE_AGE = 1209600 inside the view, which immediately modifies only the active user's session and leaves all other sessions unchanged.
B. response.set_session_age(1209600)
C. request.session.set_expiry(1209600)
D. 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?

Creating Cookies and sessions in Django Medium
A. request.session.set_expiry(0)
B. request.session.flush()
C. request.session.clear()
D. request.session.delete()

26 A registration view must create a user while ensuring that the password is securely hashed. Which approach is correct?

Creating and Managing Users in Django Medium
A. User.objects.create_user(username="mina", password="secret123")
B. User(username="mina", password=hash("secret123")).save()
C. User.objects.create(username="mina", password="secret123")
D. 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?

Creating and Managing Users in Django Medium
A. user.password = "newpass"; user.save()
B. user.password.set("newpass"); user.save()
C. user.update_password("newpass"); user.commit()
D. 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?

Creating and Managing Users in Django Medium
A. is_authenticated
B. is_superuser
C. is_staff
D. 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?

Creating and Managing Users in Django Medium
A. UserCreationForm
B. PasswordChangeForm
C. AuthenticationForm
D. 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?

Creating and Managing Users in Django Medium
A. user.can_change("blog.Post")
B. user.is_allowed("blog", "change", "post")
C. user.has_perm("blog.change_post")
D. 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?

Login and Logout URLs in Django Medium
A. path("accounts/", include("django.contrib.auth.urls"))
B. path("accounts/", include("django.contrib.admin.urls"))
C. path("accounts/", include("django.contrib.auth.models"))
D. 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?

Login and Logout URLs in Django Medium
A. /accounts/authenticate/
B. /accounts/login/
C. /accounts/signin/
D. /accounts/user/login/

33 Django's built-in LoginView is used without specifying template_name. Which template path does it look for by default?

Login and Logout URLs in Django Medium
A. auth/login_form.html
B. templates/login.html
C. registration/login.html
D. accounts/login.html

34 A project should redirect users to /dashboard/ after login when no next parameter is provided. Which setting should be configured?

Login and Logout URLs in Django Medium
A. AUTH_SUCCESS_URL = "/dashboard/", which also overrides permission checks and changes the destination of every logout request.
B. LOGOUT_REDIRECT_URL = "/dashboard/"
C. LOGIN_REDIRECT_URL = "/dashboard/"
D. 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?

Login and Logout URLs in Django Medium
A. {% url 'logout' %}
B. {% route 'logout' %}
C. {% auth_url 'logout' %}
D. {% reverse '/accounts/logout/' %}

36 A function-based view must be accessible only to authenticated users. Which implementation follows Django's standard approach?

Using Django Login in Views Medium
A. Apply @login_required above the view function.
B. Check request.session["logged_in"] in every request.
C. Apply @authenticated_user above the view function.
D. Set 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?

Using Django Login in Views Medium
A. Compare the submitted password directly with user.password, then store the username in a cookie that serves as Django's authenticated session.
B. Call create_user(), then assign the result to request.user.
C. Call authenticate(), verify the result, then call login().
D. Call 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?

Using Django Login in Views Medium
A. if request.user.is_logged_in():
B. if request.user.is_authenticated:
C. if request.user.password is not None:
D. 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?

Using Django Login in Views Medium
A. @login_required("inventory.delete_product", forbidden=True)
B. @require_permission("delete_product", app="inventory")
C. @permission_required("inventory.delete_product", raise_exception=True)
D. @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?

Using Django Login in Views Medium
A. request.session.clear() followed by authenticate(request)
B. request.user = AnonymousUser() followed by request.session.save()
C. logout(request) followed by redirect("home")
D. 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?

Creating Cookies and sessions in Django Hard
A. The theme cookie and the body OK
B. No theme cookie and the body Done
C. No theme cookie and the body OK
D. The 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?

Creating Cookies and sessions in Django Hard
A. It creates a new signature for the value
B. It raises Django's BadSignature exception
C. It returns the modified value as plain text
D. It returns 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?

Creating Cookies and sessions in Django Hard
A. Cookie deletion also requires the original value
B. The deletion must occur through session middleware
C. Cookie deletion only works for signed cookies
D. The deletion must use the matching path and domain

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?

Creating Cookies and sessions in Django Hard
A. Call request.session.cycle_key()
B. Set request.session.accessed = False
C. Set request.session.modified = True
D. Call 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?

Creating Cookies and sessions in Django Hard
A. Call request.session.flush()
B. Call request.session.clear()
C. Call request.session.clear_expired()
D. Call 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?

Creating Cookies and sessions in Django Hard
A. The expiry is ignored unless SESSION_COOKIE_AGE is changed
B. The expiry changes automatically to browser-close behavior
C. The expiry remains based on the last session modification
D. The expiry extends by 300 seconds on every read

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?

Creating and Managing Users in Django Hard
A. The password was stored without Django's password hashing format
B. The user was created without an authentication backend field
C. The password requires an active session before authentication
D. The username must first be normalized by 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?

Creating and Managing Users in Django Hard
A. models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
B. models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
C. models.ForeignKey(User, on_delete=models.CASCADE)
D. 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?

Creating and Managing Users in Django Hard
A. Convert both values to true only in the admin site
B. Store both values and rely on group permissions
C. Ignore both values and grant permissions during login
D. Reject either false value with an explicit error

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?

Creating and Managing Users in Django Hard
A. Call set_password() to invalidate permission state
B. Re-fetch the user instance before checking permissions
C. Rotate the user's current authentication session key
D. Save the existing user instance with 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?

Creating and Managing Users in Django Hard
A. create_user() hashes passwords but does not automatically run validators
B. Password validators apply only after the first successful login
C. create_user() runs validators only when the user is a superuser
D. Password validators are disabled whenever a custom backend exists

52 A project adds path("accounts/", include("django.contrib.auth.urls")) to its root URL configuration. Which statement is correct?

Login and Logout URLs in Django Hard
A. It provides login templates but requires manually defined login and logout routes
B. It exposes login and logout routes only when the admin application is installed
C. It provides named login and logout routes but not the required login template
D. It creates user registration and profile routes along with login and logout routes

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?

Login and Logout URLs in Django Hard
A. Remove the hostname and redirect to /collect locally
B. Redirect to the external URL because authentication succeeded
C. Reject the unsafe target and use the configured fallback redirect
D. Log the user out and return an authorization error

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?

Login and Logout URLs in Django Hard
A. It ignores the success URL and displays the login form
B. It raises an error rather than following a redirect loop
C. It logs out the visitor before rendering the login form
D. It redirects repeatedly until the browser stops the request

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?

Login and Logout URLs in Django Hard
A. Login goes to /dashboard/; logout goes to /signed-out/
B. Login goes to /signed-out/; logout goes to /dashboard/
C. Both login and logout go to /signed-out/
D. Both login and logout go to /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?

Using Django Login in Views Hard
A. The original URL is stored exclusively in the session
B. Only the original path is placed in the next parameter
C. Only the original query string is placed in the next parameter
D. The original path and query string are placed in the 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?

Using Django Login in Views Hard
A. class EditView(UpdateView, View, LoginRequiredMixin):
B. class EditView(UpdateView, LoginRequiredMixin):
C. class EditView(LoginRequiredMixin, UpdateView):
D. 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?

Using Django Login in Views Hard
A. Pass the user's password hash directly to login()
B. Pass the appropriate dotted backend path to login()
C. Save the backend name in the user's database row
D. Set 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?

Using Django Login in Views Hard
A. It is preserved under a newly rotated session key
B. It is flushed along with the authenticated session
C. It remains until SESSION_COOKIE_AGE expires
D. It is copied into a signed browser cookie

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?

Using Django Login in Views Hard
A. The cart data is moved into the user's database record
B. The session is flushed and the cart data is discarded
C. The session key is cycled while the cart data is retained
D. The existing session key is retained without any rotation