Django Django Views & URLs 1 — Questions and Answers
Question 1: What is the difference between a function-based view (FBV) and a class-based view (CBV) in Django?
- FBVs are plain functions; CBVs are classes that inherit from Django view classes (Correct answer)
- FBVs are faster; CBVs are slower
- FBVs support only GET; CBVs support all methods
- FBVs are deprecated in Django 4+
Correct answer: FBVs are plain functions; CBVs are classes that inherit from Django view classes
FBVs are Python functions taking a request and returning a response, while CBVs are classes that provide built-in mixins and method dispatch for HTTP verbs.
Question 2: Which decorator restricts a view to logged-in users only?
- @login_required (Correct answer)
- @auth_required
- @requires_login
- @authenticated
Correct answer: @login_required
@login_required redirects unauthenticated users to the login page and is imported from django.contrib.auth.decorators.
Question 3: What does `path()` do in Django's URL configuration?
- Maps a URL pattern to a view function or class (Correct answer)
- Generates absolute URLs
- Defines URL namespaces
- Creates URL redirects
Correct answer: Maps a URL pattern to a view function or class
path() is used in urls.py to associate a string-based URL pattern with a view, supporting type converters like <int:pk>.
Question 4: How do you capture a URL parameter as an integer in Django's path() routing?
- <int:pk> (Correct answer)
- [int:pk]
- {int:pk}
- (int:pk)
Correct answer: <int:pk>
Angle brackets with a type converter like <int:pk> capture and automatically convert the URL segment to a Python integer.
Question 5: Which HttpResponse subclass performs a permanent redirect in Django?
- HttpResponsePermanentRedirect (Correct answer)
- HttpResponseRedirect
- HttpResponseMovedPermanently
- HttpResponseForward
Correct answer: HttpResponsePermanentRedirect
HttpResponsePermanentRedirect returns a 301 status code, while HttpResponseRedirect returns a 302 temporary redirect.
Question 6: What function reverses a URL pattern by name in Django?
- reverse() (Correct answer)
- resolve()
- url()
- geturl()
Correct answer: reverse()
reverse() takes a URL name and optional arguments to generate the corresponding URL string, avoiding hardcoded URLs.
What is the difference between a function-based view (FBV) and a class-based view (CBV) in Django?