Understanding function-based views
As the name implies, function-based views are implemented as Python functions. To understand how they work, consider the following snippet, which shows a simple view function named home_page
:
from django.http import HttpResponse def home_page(request): Â Â Â Â message = "<html><h1>Welcome to my Website</h1></html>" Â Â Â Â return HttpResponse(message)
The view function defined here, named home_page
, takes a request
object as an argument and returns an HttpResponse
object with a Welcome to my Website
message. The advantage of using function-based views is that, since they are implemented as simple Python functions, they are easier to learn and also easily readable for other programmers. The major disadvantage of function-based views is that the code cannot be reused and made as concisely as class-based views for generic use cases. The next section is a brief introduction to class...