This is part of the series Django For Beginners we are going to see about apps in app and we will see about models in django in this part.
You can this read complete post here.
In this post we are going to understand the idea of views and routing from scratch and see some types of responses and then we will learn about basic routing and to separate
urls.py in separate files files.
what are views ?
Views are like middle man between request and response on your server they contain all you logic for a route, we will talk about route later in this post. They essentially process get the data needed for the request and process it and the return it as a response. This response can be of a variety of types,
xml to name a few.
Now let's see a example of a view,
from django.http import HttpResponse def home_response(request): return HttpResponse("Hello World 😊.")
I tried to make is as basic as possible. What is happening above is when we receive a request and we call this
view function it will return an simple text response, that is
Hello World 😊. .
You may have noticed about
request argument in the
home_response view above it is compulsory argument it is a
dictionary object and contains lot, by lot, I mean really a lot of information about the request of which most of the times you are not going to use directly. With
request object we can access headers, user agent, ip, cookies to name a few.
In above example we returned
text response but it is not what happens in real world, right 🤔 ? In real world scenarios we need to either prove a html response or a
xml as a response. So let us see how to pass
html as response for now.
from django.http import HttpResponse def home_response(request): return HttpResponse("<h1>Hello World 😊.</h1>")
Returning HTML Pages in Response
I am lazy so I copied above code and just added
<h1></h1> tags around our plane text response and wallah, it is now a
html response but don't you think it would be bad for long html responses with which we have to deal most of the times, so for that we keep
html away from
views all together so to keep code clean and follow the
DRY principle .
Sorry to interrupt you but I want to tell you one thing that I have started a small blog you may continue reading it here it will help me a lot.
Top comments (0)