A view function/class, or view for short, is a Python function that takes a web request and returns a web response.
from django.http import HttpResponsedef index(request):return HttpResponse("<h1>Welcome to my homepage!</h1>")
HttpResponse
is used to provide an inbound HTTP request to a Django web application with a text response.
HttpResponse("Response here")
URL routes are configured in urls.py by calling the path()
function to the urlpatterns
list.
urlpatterns = [path(""home/"", home_view),path(""about/"", about_me_view),]
Dynamic URLs can be created by using angle brackets (<
, >
) to capture named parameters inside of a path()
function.
# URLconfigurlpatterns = [path("profile/<str:name>", profile_view),]# views.pydef profile_view(request, name):return HttpResponse(f"Hey there! My name is {name}")
The render()
functions take three arguments- the request variable, the template path, and optionally a dictionary object to pass data to the template.
render(request, "template.html", { "data": your_data })
An Http404
exception can be raised inside a view function and returns a built-in 404 page provided by Django.
from django.http import Http404def blog_view(request, slug):try:entry = Blog.objects.get(slug=slug)except Blog.DoesNotExist:raise Http404()return render(request, "blog/post.html", {"blog": entry})
The name
parameter can be provided inside the path()
function in order to dynamically render it within the route’s template. The route will be accessible via the named parameter that’s passed on.
<a href="{% url 'name_of_path' %}">Contact Me</a>