Ever heard the word “Django”? Most answer going to be ‘YES’
Not this one, I mean Python web framework = Django. If YES then congratulations you just have to read the blog completely else then congratulations you just have to read the blog completely.
Let’s get started:
What is Django?
Django is a web framework based on python that allow to create web application with ease. It is robust, monotype in nature, easy to understand and believes in less code(relief) by making the code reusable but how? We will see this later in example.
There are a lot of web framework present there then why Django? We also have a brother of Django called Flask then why Django? The answer is “Django is quite intelligent and meant for full stack development. It works on the concept of Models — Template — View (MTV) and have data models that helps to connect the classes to the databases.” I know there are some rough term but do not take tension as I am going to explain every single word. For more click here.
Enough talking let’s go for practical:
- installing Django in windows: “ pip install django ” on command prompt or cmd.
- installing Django in Linux: “ pip3 install django ” on terminal(pip3 is for python3).
Now import django module and use it! Wait a minute if we create a lots of scripts containing django module how django differentiate the scripts like which one is going to be used as HTTP Response or as a data base structure? For this Django provide a command “django-admin” to create a project and all script under one umbrella. I told you it is monotype in nature, user cannot create any script file and load it, user have to create or update according to django own files(user is dependent on the django script structure).
i ran the django-admin command and it list the available subcommand that used to create magic. Now I have to create a project on which I can work, let’s check the subcommand for this… I got the word project in subcommand “startproject” so I’m going to use it:
django-admin startproject “name_of_the_project”
A directory/folder named Reader is created and from inside it look like this:
A manage.py file and a “reader folder” again? When a project is created a subfolder with same name is also created that contains the settings and other important script files of the project. The manage.py is very important script file, it is like the wand that helps to cast the magic.
When you install the django you will get the location of installation. When you go there is a file named “entry_points” that contain:
Now relate the last two snapshot you will get a better understanding. “sys.argv” is used to take the input from command line.
As the project is created all you have to call the manage.py that acts as a “django-admin” command and takes subcommands as input.
Let’s check whether our project is running or not, For this we have to launch our web application on localhost(on your local computer/personal laptop) and we use runserver subcommand for this:
Now, go to the link provided by django:
Project is running successfully, congratulations to you!
First practice till here then move to next part.
After that let’s create a homepage for our project. Every webpage in Django is a web application that has its own files.
I wrote a simple HTML snippet for homepage that resides in reader project.
It’s working fine when I double click on the file but how django will access this file, like by the URL provided by runserver subcommand ?
I tried http://127.0.0.1:8000/homepage.html but an error came. The error is
It says reader.urls is not configured for the homepage.html that’s why django is unable to find and display the homepage. Then check the reader.urls file to remove the error.
Its a python script. So why URLS.py needed to be configured. URLS.py file used to route the user to different pages. Every single front-end file that is used to display the content to the client must be linked in URLS.py
You can see there is a path given in urls.py, then go for it to understand what urls.py is for
When I go to http://127.0.0.1:8000/admin above page appears that means this page is linked in urls.py so it can be accessed by the URL provided by django runserver subcommand.
Now we have to connect our webpage to urls.py:
When I tried to add the URL as written for the admin, I got an error (django is so intelligent when you run the server and there is an error in your program it will tell you in which part the error comes) ‘homepage’ is not defined. And we can also understand from the example written in URLS.py that this way is not legitimate.
Then how we can display our webpage?
Django understand that every webpage is a web application so it has settings for an application not for a single webpage that we are trying to display. So, the correct way to create a homepage is to create a web application that will display the homepage or become our homepage.
Creation of web application in a project:
To create a project we used “django-admin startproject reader” and we also know that when a project is created the “manage.py ” work as django-admin for the project.
Now to create a application we going to use manage.py:
This is how an application folder looks like. Let’s understand some basic terminologies here:
- __init__ file: it is used to initialize your application. It has nothing inside but important file.
- admin file: The database you have created for your this application should be registered here than you will able to use the tables of database to fill the data.
- apps file: It contains configuration for this application.
- models file: This files connects the application to the database. Here we create the tables, columns etc. depending on the database you choose(default dB is SQLite3) and you don’t have to memorize the SQL query, just python.
- tests file: for testing the program.
- views file: It contains what user/ clients see or what t be displayed on the browser.
Moving to practical usage: We have to display the homepage content so we have to edit views.py file of the homepage app.
Except the first line all other line are written by me right now. What I have did? I imported HttpResponse from django.http to return a response/data/information to the client who requested the homepage. home(request) takes the request from client and return the string “Hello…..project”. Actually we really don’t need HttpResponse method in real production environment, RENDER is used to response to a request.
Now we have to add this file into reader.urls so django can collect the data from here and display on browser.
Updated the urls.py for the homepage app but how I know what to write here for connection? Django helps me in these cases, it provides examples in the form of comments(green color statement) so I can add the path without any other help.
If still there is any confusion — Django’s official documentation is here to help.
Let’s run the project using runserver:
Kudos! we got our result.
“You can try ‘<h1>Hello everyone My name is Homepage and i live in django’s reader project</h1>’ ” in the place of string in views.py
Templates And Models
What is Templates?
Basically template is like a person with changeable body parts that is you can not create a human (except of that method) on your own but if you get a whole body ready you can change the structure like changing your face by plastic surgery or makeup, shape by going to gym or steroids'.
This is what django understand html files provided by you, it just use it for change the working of web page by making it dynamic in nature.
Now how to render the templates to be used by django?
It can be render by using render() with some arguments/ For example: “return render(request, ‘template_name_with_location’)”.
You can see the argument ‘template_name_with_location’ we have to pass the template name here. To do that we need to create a folder with name ‘templates’ then place template files. Let’s see with these examples:
I created a folder ‘templates’ and subdirectory ‘homepage’ then place my template named ‘first_page.html’ which look like this:
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<h2 style=”text-align:center”>Welcome to Testing Environment where developer is tested!</h2>
Observe the template name and the address where it is stored.
Now I’ll run the server to check whether django is rendering or not.
This is my views.py and urls.py
In views.py I rendered the template from template folder and then gives a path to access the web page. When I hit the URL ‘127.0.0.1:8000/index’ this comes up:
It says “TemplateDoesNoteExist” it is an error but why?
Actually you know where the templates exists but how django comes to know in the whole project where templates exits?
So, we have to manually tell the django where templates resides and to configure django we have to edit settings.py. Basically we have to provide the address of templates.
So, I open the settings.py and figuring out how to give the address. While searching thoroughly I got a variable called “BASR_DIR” that contains the address to our project and above that in comment i got the way to insert a new address. Basically if we concatenate BASE_DIR further with our templates location then we all done. See how:
now it will work? NO
Because we just save the path in the variable. Now scroll down in settings.py and you will get a variable called TEMPLATE where all the configuration related to templates is placed so there we have to place the address like this:
Save the setting and try again.