Django Introduction An Easy To Go Web Framework


 

When I first got interested in web development, like any other enthusiast, I learned HTML, CSS, and some javascript and created a normal good looking webpage and then I am like wooo man you are a web developer now. But then the concept of backend pops up and I am like wooo this shit is scary, I am way far to become a web developer...

Backend involves many things, like URL routing, and managing forms get-post requests, securities, dynamic webpages, how servers work, how to set up one, and what the hell is a web server.

You know, life was simpler when you know HTML and CSS, but man, all those above pieces of stuff, kind of scary right? at least for me, but yeah if you like those things you might fall in love with them and kind of find your way out. But things should be simpler right? And that's were our Lil friend Django comes in.

Django says, Okay buddy I got you, I will handle those things, but only one thing is that you should know about python. I work with Python, Python is easy and that is why I am.

Django is a super amazing web framework you can go to their official website and read all the documentation and tutorials here.

Now, Let's actually talk about what we meant by Backend and how Django helps us.

We have read what is HTTP response cycle is, you enter your URL to the browser, and then the browser takes your request to the corresponding web server, then web server understands your request and then generates a response back to it and that response is just another webpage.

Now, where is the Django in all these steps? Django covers all the parts were the web server understands your request, and generates a response to it in a form of a webpage. That's what the backend is. understanding the user request, fetching required data from the database, and generating a response according to it.

Now, generating response is the main thing, right? you understand the user's request, now according to that request, you have to generate the response.

URL Routing In Django

Take this example, you write the URL www.example.com/books/moral, Now, the browser will contact the server of www.example.com and sees the URL pattern, Now it says that okay go to the 'books', 

Then it will look where the 'books' is located, if it founds then okay, further is 'moral', okay search for  'moral', we found the moral great, proceed to the next step.

The above step is URL Routing, we first understand, where to look and where to go.

After URL routing, The next step is generating a 'View', That is, you have to generate a webpage according to it, How you do it? By understanding the user's request, right? According to it, you have to generate a view.

Views In Django

'View' is what we see, the look, the feel of the webpage. Now, okay we understand the URL Routing, Then View, Now what to show the user? The user is expecting some data right? maybe, the above URL,  just lists out the books whose genre is moral, i.e we have to create a view which can list out the books with genre moral.

If we remember the concept of the HTTP request and response cycle, Actually what's happening is, we as a user, when visit any website, request some data. And the data is shown to us as an HTML page,

Now, the data is retrieved from the database, according to the user's request, right? If I want the list of books with genre 'self help', I have to generate the data, and the 'web page' according to it.

So, if your website has let's say 5 geners, 'moral', 'self help', 'thriller', 'science fiction', 'fantasy', will you create 5 web pages? NO! offcourse not, And that's where the notion of dynamic web pages comes into play, and for this the django views will help us.

Let's understand this with an example:

Suppose you have a database with these two tables, a simple one just for example:

bid bgenre
1 moral
2 self help
3 thriller
4 science fiction
5 fantasy


book_id bname bid
1 The Moral Landscape 1
2 The 48 Laws Of power 1
3 The virtue Of Selfisness 1
4 The Secret 2
5 Think And Grow Rich 2
6 The Guest 3
7 Before I go to sleep 1

Now, User can request any data, right. So, You have to create a view which handles the request dynamically. How we do that? have you ever observed a URL like this www.example.com/books?bid=1

The part with books?bid=1, is a way to tell the server, okay go to the database and fetch the view with data were bid is 1.

So, In short we generate the views like that, dynamically!

We have to contact to our database, okay give me some data of book author, yeah some SQL queries will be performing okay, I don't wanna go there just fetch me the book names with the author who writes the moral books.

And then we took these data, we append it to our view then just shove it back to the User. Simple, That's how a website is working. A whole lot of fuss right, so much thing to do.

And to learn those things, puff my mind just blows up.

But, then Django comes, says, man, I am here I will do those things, Don't worry you will be a web developer, I am gonna help you.

And there we go, Off to learn Django. Cause we want to be a web developer right. cool stuff.

So, let's write a few lines of code, and launch your first website right now. yeah, it's that easy...

okay, we have to create a virtual environment first, but, I don't know how to set up one, what is a virtual environment? Just read it here. Install  anaconda, It will be easy.

1. Creating a Virtual Environment

conda create -n learnDjango

The above command will create a virtual environment with the name learnDjango, The reason we are doing this is to just be sure that if we mess up at any point, our real machine will not get effected or to just separate our work from other projects.

2. Activate a Virtual Environment

conda activate learnDjango

3. Install Django

conda install django

Now, We will create our first project in Django

4. Start A Project

django-admin startproject first_project

This will create a folder, 'first_project', when you go there you will find some files and these are some files which will do all the heavy lifting of backend for us.

Before moving further, Just install 'atom text editor', to help us code efficiently.

In the atom text editor open your 'first_project' folder.




Okay, So we have some files right? Let's meet them.

When you go to your first_project directory, you will see two files:
  • first_project (folder)
  • manage.py
manage.py is the file that is responsible for managing our project, we will use this file to launch the server and other stuff.

first_project

When you go into this folder, you will see these files:
  • __init__.py
  • asgi.py
  • wsgi.py
  • urls.py
  • settings.py
The asgi and wsgi files are not required to understand right now, cause they are for dealing and managing servers when we launch our project on the internet. For now, we need to understand urls.py and settings.py

urls.py

Remember, In the above paragraph I explained to you about URL routing? It's like understanding the URL and finding the perfect view or HTML page.

urls.py does exactly that. we will use this file to map different URLs of our website.

settings.py

This file is responsible for handling various functions of the website, like database engines, templates directories, and all.

launching Website

Now, Time has come to launch our first django website, type the following command whenever you want to check the working of you website when in development phase:

Go the project directory where the manage.py file is and just type:

python manage.py runserver

If you get an error, that the 8000 port is in use, then use can also run this command:

python manage.py runserver 8080

This will run your server on port 8080.

You will see something like that in your command prompt.

   Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).


  You have 18 unapplied migration(s). Your project may not work properly until
  you apply the migrations for app(s): admin, auth, contenttypes, sessions.

Run 'python manage.py migrate' to apply them.
September 24, 2020 - 16:21:29
Django version 3.1, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.

Go to that URL and that's it if you see a rocket launching, then django is on!

This is it. Going to all the above files and understanding them is learning the django. In this post, I will talk about the concepts over which django is based.

If you want a full fledged tutorial then visit this page on django official tutorial, But that tutorial is lil bit confusing for beginners, as we don't know the basic concepts. So go to that link, and come back here whenever you don't understand a concept.

if you ask me a roadmap to learn django, I will say:

  • Introduction (like this page)
  • Managing DataBases In Django
  • Learning How To Show Views and Templates
Let's talk more about templates,

Django Templates

Templates is like writing a HTML web page but using python! yeah, python is now everywhere. You have to learn how to write a HTML page using Django's template language.

If you wanna see what django templates looks like and what are they, read the official document here.

They have ways to define a variable, loops and many more, It's like total replacement for javascript, May be in future, Django's template language will be more powerful and can able to do more stuffs than javascript.

One more interesting thing is Django tempates can automatically handles cross-site scripting attack. It support built-in functionality of escaping special tags and characters making your security in a minutes.

Django's DataBase Models

Now, if django is providing everything in python, even writing web pages then how it can not create a way to manage database queries in python!

Django provides us a whole new concept of building databases and doing queries using it's models class.

For example, Remember, we create a tables in SQL like:

create table bookgener(bid int NOT NULL, bgener varchar(25) PRIMARY KEY(bid));

But, Django say's, buddy, we have to work in python, write that code in python!

Now, How to write this thing in python? Django has an library called as django.db

What we will do is, We will create a class which is an extension of models.Model available in django.db.

Creating table in Django Using Model


Let me show you a example:


from django.db import models

class BookGener(models.Model):
	bid = models.IntegerField(primary_key=True)
    bname = models.CharField(max_length=100)
   


This is the way to create a table 'BookGenre' in django. You can read the official documentation of django models here

Let's understand how we can adopt this way of using the databases. I will realete each thing using sql queries and then using the django's model code.

In sql queries, we use 'create table <table name>(varname type constraint,
                                                                                varname type constraint,);

The django, converts all this into an object oriented way using his models class.
So, If you want to create a table, Then in Django, You have to create a class with that table name.

The variables or data members of that class will be the columns of that table.

Now, As you know, we datatypes and then constraint concepts in SQL queries. Django handles this using his models.Feild class.

So, as you can see in above example, I want to make the bid as int and give that as primary key constraint, I used:

bid = models.IntegerFeild(primary_key = True)

Similarly we have many fields for different variable types as you use in SQL. Read about them here.

So, This is about creating a table, If you want to create a table, then you have to define the class according to it.

Insert Data In Django Model Table


But, what if we need to Insert the data? Simple, You have created the class now you have to create it's objects and then, feed the variables with data.

For, example, If I want to add a row in the above table I will write:

bg1 = BookGenre(1,'Moral')

Then to save this data to the database, use:

bg1.save()

Retreiving Data From Django Model

To retrieve data, Django uses a query manager called as objects.

For example see this:

BookGenre.objects.all()

This is same as select * statement.

The output will be:

<QuerySet [<BookGenre: BookGenre object (1)>]>

Now, this is like a sequence datastructure in python, You can perform slicing, indexing to get the 'objects'

For better understanding let's put some more data in our table:

b1 = BookGenre(2,'self help')
b1.save()
b1 = BookGenre(3,'thriller')
b1.save()
b1 = BookGenre(4,'science fiction')
b1.save()
b1 = BookGenre(5,'fantasy')
b1.save()

Now, use the objects.all() to get all the saved data.

BookGenre().objects.all()

Output:

    <QuerySet [<BookGenre: BookGenre object (1)>, <BookGenre:
    BookGenre object (2)>, <BookGenre: BookGenre object (3)>,
    <BookGenre: BookGenre object (4)>, <BookGenre: BookGenre object
    (5)>]>
  

But this looks so absurd, cause we have a habbit of SQL, we write select * BookGenre and we got the data.

But, In django, These are objects, right? So it returns a list of objects. But we can also return a the values inside it.

Use values()

BookGenre().objects.all().values()

Output:

    <QuerySet [{'bid': 1, 'bgenre': 'moral'}, {'bid': 2, 'bgenre': 'self
    help'}, {'bid': 3, 'bgenre': 'thriller'}, {'bid': 4, 'bgenre': 'science
    fiction'}, {'bid': 5, 'bgenre': 'fantasy'}]>
  

It, return a list, dictionary elements as each element.

Filters In Django Model

We don't always perform the select * operation in SQL, right? sometimes we use where clause to put conditions for retrieving the necessary data.

So, Django model also provide this functionality by its filter() function.

I recommend to see this documentation to get a idea of how to use conditions while retrieving the data.

Here I am listing some important django official documentation you should read while working with django models

This is all about django. what you need to learn the most is Django's template language and Django's data models. And then you can create any website within a snap.

Read this official Django Tutorial to get started, As you have a clear idea about what is Django and how it is working you are ready to take this official tutorial by django's official website.

Post a Comment

0 Comments