Overview
In my previous blog, I taught you how you can get started with Django, How to create a Project and an App and set up its configurations.
But it won't be worth it if you keep typing and can't even see the results, whether your app is working or not. So in this blog, I will tell you how you can run your application on your local server, How to attach your HTML files with your Django backend, What are Templates and Static files, Django's template syntax and much more.
Run Sever
To get started open your terminal and start your Django project and inside your project create your app (As it told you in the previous blog)
Now, open your terminal and type python manage.py runserver
. This will run your web application on your local host.
Now, Follow the link
Once you click on the link you will see this interface. This is Django's Default interface.
Creating Routes
Every Website has different URLs and every URL has its different sub - URL. So go ahead and create a urls.py
file in your app directory (same as shown below)
Now, open the urls.py
file of your main project and include the URL of your app.
This will tell your project to include your app's urls.py
to the main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls'))
]
Response and Request
So far, you have successfully included all the necessary configurations in your project. It's time to create our first webpage
Go to the views.py
file in your app directory and import HttpResponse
(same as shown below). Now, create a function that will take a request and return a response. In this case, we are just going to return Hello, World!
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello, World!')
Now, go to urls.py
file of your app which you just created above and import views from your current directory. Now, create a list of urlpatterns
and add the path of your index function to it.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Now, go to the terminal and run python manage.py runserver
Click on the link.
After clicking the link you will see this interface. That's because we have not entered the route of our app yet which we created previously.
So, Type the route of your app.
and VOILA! you are live with your first web page.
But whenever we visit a webpage or generally a website, we don't see Hello, World!. We see our names such as Hello, Akshay!
To achieve this we have to pass a variable into our function and then take the input from the user.
Create a function named greet. The greet function will take a request and a name as input and return a response with the name.
def greet(request, name):
return HttpResponse(f'Hello, {name}!')
To take input from the user all we have to do is instead of defining our route name by ourselves we can ask the user to enter their route by taking a string as input <str:name>
this will indicate to the browser that whatever string is entered by the user, use it inside the name variable and return the HttpResponse
accordingly.
urlpatterns = [
path('', views.index, name='index'),
path('<str:name>', views.greet, name='greet'),
]
Templates
So, far you have you have seen how Django takes a request and returns a response.
No, Let's see how we can integrate our HTML documents with Django.
Django is a Framework and frameworks follow a structure. Similarly, while creating an HTML document inside our Django project we have to follow a structure or a hierarchy. Go to your app directory and create a folder named "templates" Inside your templates folder create another folder name exactly as your APP_NAME.
Now, go to your views.py file and render your HTML document inside your index function.
def index(request):
return render(request, "myapp/index.html")
Your HTML document should be as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Run the server and you will see the output as follows:
This was pretty simple, right? Just create a document render it inside our function and Done!. But what about our greet function? How are we going to use a variable inside an HTML document? Well Turns out that Django uses Dictionaries to render a variable inside an HTML document and {{VARIABLE_NAME}} to use that variable inside our document.
def greet(request, name):
return render(request, "myapp/greet.html",
{
'name':name
})
Here, we are telling our greet function that please render the template named greet and pass this name variable inside our greet.html
as "name". So our HTML file will look something as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Greet</title>
</head>
<body>
<h1>Hello, {{name}}</h1>
</body>
</html>
And when we run our project the output will be the same as we expected.
Is It New Year?
Just keep saying Hello is quite boring! So now, we are going to create a clone of the website https://isitchristmas.com/ if you don't know about this website then its only functionality is to tell whether it is Christmas on the current date or not. if you will visit this website on 25 December it will say Yes, else No.
We are going to create a website to tell us whether it is the new year or not. To do that we are going to use a Python library called datetime
. This library has a method called now
which we can use to check the current date and time.
So, go ahead a create another app named as isitnewyear
python manage.py startapp isitnewyear
add its route to the urls.py
inside out project directory.
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
path('isitnewyear/', include('isitnewyear.urls')),
]
add our app to the installed apps in settings.py
create another urls.py
file inside our isitnewyear
app and import path
from django.urls
, import views
from .
(CURRENT_DIRECTORY) and create a list of our routes called as ulrpatterns
. For this app, we are just going to create a single view so you should add that view into urlpatterns
and keep its route as an empty string.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
Now, create an HTML document isitnewyear ๐๐ป templates ๐๐ป isitnewyear ๐๐ป index.html
It's time to create our view.
inside our views.py
file, import the datetime
module and create a function named index. inside the function store the datetime.datetime.now()
method inside a variable.
render the HTML document and pass this variable to the document as shown below:
from django.shortcuts import render
import datetime
def index(request):
now = datetime.datetime.now()
return render(request, "isitnewyear/index.html", {
"newyear" : now.day==1 and now.month==1
})
The newyear
stores the condition that if it is the first day of the first month of the year, then it will return True, else False.
Now, to check whether it is the new year to not we have to use if else statements. and luckily Django's templating syntax makes it so easy for us.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Is It NewYear</title>
</head>
<body>
{% if newyear %}
<h1>YES</h1>
{% else %}
<h1>NO</h1>
{% endif %}
</body>
</html>
To use control or conditional statements inside our templates we can use the above syntax and once our statement ends we have to define the end.
Now if you run the server and visit our route "isitnewyear".
Static Files
A web page without CSS is incomplete and Django's best practices state that we should keep our templates (HTML files) and our static files such as CSS or JavaScript files separately. To do that create a static folder inside our app directory and then inside that another folder same as our app name and then our css file isitnewyear ๐๐ป static ๐๐ป isitnewyear ๐๐ป styles.css
To link our static files to our HTML doc. we have to first load it and then use this syntax inside our <link>
tag: {% static 'isitnewyear/styles.css' %}
. This tells our template that the File we are trying to link is static and inside this particular directory.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Is It NewYear</title>
<link rel="stylesheet" href="{% static 'isitnewyear/styles.css' %}">
</head>
<body>
{% if newyear %}
<h1>YES</h1>
{% else %}
<h1>NO</h1>
{% endif %}
</body>
</html>
Now add all the CSS you want and run the server.