Best Python Django Tutorial For Beginners – With Project Structure

Python course with 57 real-time projects - Learn Python

In our last tutorial, we discussed How to Work with Relational Database with Python.

In this Python Django tutorial for beginners, we will see how to install Django Python.

Moreover, we will study the history of Python Django and MVT Pattern.

Along with this, we will cover Python Django features and how to create an application in Python Django.

At last, we will cover the structure of the project in Python Django.

So, let’s start the Python Django Tutorial.

Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial For Beginners

What is Python Django?

Django is a high-level Python framework.

It is free and open-source, written in Python itself, and follows the model-view-template architectural pattern.

We can use it to develop quality web applications faster and easier. Since developing for the web needs a set of similar components, you can use a framework.

This way, you don’t have to reinvent the wheel. These tasks include authentication, forms, uploading files, management panels, and so.

Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial For Beginners

Python Django Tutorial – Install Django

To work with Django on your system,
C:\Users\lifei>pip install Django
Collecting Django
Downloading https://files.pythonhosted.org/packages/ab/15/cfde97943f0db45e4f999c60b696fbb4df59e82bbccc686770f4e44c9094/Django-2.0.7-py3-none-any.whl (7.1MB)
100% |████████████████████████████████| 7.1MB 610kB/s
Requirement already satisfied: pytz in c:\users\lifei\appdata\local\programs\python\python36\lib\site-packages (from django) (2018.5)
Installing collected packages: django
Successfully installed django-2.0.7

Python Django Tutorial – Serving a Request for a Website

Let’s first find out, in layman’s terms, what happens when your server receives a request for a website.

The request is passed to Django and that tries to analyze this request. The urlresolver tries to match the URL against a list of patterns.

It performs this match from top to bottom. If it can find a match, it passes the request to the view, which is the associated function.

The function view can check if the request is allowed. It also generates a response, and then Django sends it to the user’s web browser.

Python Django Tutorial – History

  • Adrian Holovaty and Simon Willison created Django in the fall of 2003 at the Lawrence Journal-World newspaper
  • Django publicly released under a BSD license in July 2005; named after guitarist Django Reinhardt
  • Today, Django is an open-source project with contributors around the world

Python Django Tutorial – MVT Pattern

MVC stands for Model-View-Controller. We use this when we want to develop applications with user interfaces. MVT stands for Model-View-Template.

A template is an HTML file mixed with DTL (Django Template Language).

Django takes care of the Controller part, which is the software code and controls the interaction between the other two parts- Model and View.

When a user requests for a resource, Django acts as a controller and checks if it is available.

If the URL maps, View interacts with the Model and renders a Template. Python Django sends back a Template to the user as a response.

Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial For Beginners

The model helps us handle database. View executes business logic and interacts with Model to carry data.

It also renders Template. Template handles the user interface and is a presentation layer.

The Model class holds essential fields and methods. For each model class, we have a table in the database.

Model is a subclass of django.db.models.Model. Each field here denotes a database field.

With Django, we have a database-abstraction API that lets us perform CRUD (Create-Retrieve-Update-Delete) operations on mapped tables.

Features of Django

When working with Python Django, you can expect the following Django Features-

Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial – Features of Django

1. Scalability

When you need to scale your system, you can simply add more web nodes to your Django.

That is, you can scale it horizontally. Two products that use Django’s scalability are Disqus and Instagram.

2. Portability

The portability of Python makes for a portable Django too. Various platforms include Windows, Linux, and MacOS.

3. Security

Python Django ensures some arrangements for security too. One of these is that it stores hashed passwords in cookies.

4. Versatility

Python Django will work with formats like HTML, JSON, XML, among others. It also supports many different client-side frameworks.

So, we can use it to build anything including regular websites and social networks.

5. Packages

Django Programming has the foundation of thousands of additional packages.

6. Ease of Use

Features like the built-in admin interface make it easy to build with Django. It is also fully functional and finds it easy to switch databases.

Prerequisites to Creating a Project in Django

In this Python Django Tutorial, we will study the prerequisites to create a project in Python Django.

1. Starting Project

Use the following command in the command prompt to begin your project-

C:\Users\lifei\Desktop>django-admin startproject project0

Then move to this folder.

C:\Users\lifei\Desktop>cd project0

C:\Users\lifei\Desktop\project0>

2. Running the Server

You could apply these migrations before you start your server-

C:\Users\lifei\Desktop\project0>python manage.py migrate

Now, start the server-

C:\Users\lifei\Desktop\project0>python manage.py runserver

Performing system checks…

System check identified no issues (0 silenced).

July 08, 2018 – 21:51:39

Django version 2.0.7, using settings ‘project0.settings’

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

If you see something like this, it means you have successfully installed Django:

Python Django Tutorial - Prerequisites to Creating a Project

Python Django Tutorial – Prerequisites to Creating a Project

3. Setting up a database

For our project, we have set up MySQL: http://www.mysql.com/

Python also supports other database products like Oracle, SQLite 3, MongoDB, PostgreSQL, and GoogleAppEngine Datastore.

4. Web Server

While Django has its own lightweight web server, you can also use your own- like Apache.

Django Project Structure

This is what your project directory will look like:

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – Project Structure

1. manage.py

This script lets us interact with our project using the command line. Facilities include starting up the server and syncing to the database.

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – manage.py

2. Project folder

This holds the packages for our project-

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – Project folder

  • __init__.py- A Python package.
  • settings.py- This holds website settings like database configuration details.
  • urls.py- This holds links in your project and the function(s).
  • wsgi.py- This deploys our project over WSGI and helps the app communicate with the web server. WSGI stands for Web Server Gateway Interface.
  • __pycache__- This directory holds files like __init__.cpython-36.pyc, settings.cpython-36.pyc, urls.cpython-36.pyc, and wsgi.cpython-36.pyc.

In settings.py, DEBUG is set to True.

This is okay at the time of deployment, but you should set it to False when working with a live project.

This is because this gives out information about errors in your project.

Another construct you will find in this file is-

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

3. db.sqlite3

This is the database file for your project and has the extension .sqlite3.

Creating an Application

Let’s learn how to create an application in Django by this python Django Tutorial. Projects are modular.

A contact form is one such application, and you can borrow it from one project for another.

You can start an application this way:
C:\Users\lifei\Desktop\project0>python manage.py startapp app0

This creates the following contents in the directory project0:

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – Creating an Application

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – How to Create an Application

  • Migrations- This holds another __init__.py file.
  • __init__.py- This is a Python package.
  • admin.py- This lets us make the app modifiable in the admin interface.
  • apps.py- This holds the names of all your applications.
  • models.py- This holds all application models.
  • tests.py- This holds unit tests for the project.
  • views.py- This holds the application views for the project.

In your settings.py, you can add your app name in the INSTALLED_APPS construct-

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app0'
]

Python Django Admin Interface

Here, in this Python Django Tutorial, we are going to see how to use Django Admin Interface?

Using the Django admin interface, you can perform CRUD operations on the model.

This interface depends on the django.countrib model; it is enabled by default.

You can find it as ‘django.contrib.admin’, in INSTALLED_APPS in settings.py.

To access this interface, you can try one of two methods-

  • 127.0.0.1:8000/admin
  • localhost:8000/admin

You get something like this:

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – Admin Interface

1. Creating a Superuser

To create a superuser, you can push in the following command-

python manage.py createsuperuser

Once you’re done creating a superuser, use this username and password to login to the dashboard.

Best Python Django Tutorial For Beginners (Advanced 2018)

Python Django Tutorial – How to Create a Super use

How to Create Simple Project in Django?

We can create a simple view using the following code-

>>> from django.http import HttpResponse
>>> def hello(request):
      return HttpResponse("Hello")

We save this file as views.py in the inner project0 directory.

This is how we can import it-

>>> os.chdir('C:\\Users\\lifei\\Desktop\\project0')
>>> from project0.views import hello

1. Mapping to a URL

Now in the inner project0 directory, you have a file urls.py. It looks something like this-

“””project0 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:

https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:

Function views

  • Add an import: from my_app import views
  • Add a URL to urlpatterns: path(”, views.home, name=’home’)

Class-based views

  • Add an import: from other_app.views import Home
  • Add a URL to urlpatterns: path(”, Home.as_view(), name=’home’)

Including another URLconf

  • Import the include() function: from django.urls import include, path
  • Add a URL to urlpatterns: path(‘blog/’, include(‘blog.urls’))

“””

>>> from django.contrib import admin
>>> from django.urls import path
>>> urlpatterns = [
        path('admin/', admin.site.urls),
]

In this, the urlpatterns tuple maps URLs to views. Add this line of import to urls.py:
from project0.views import hello

And then add this value to your urlpatterns tuple:

path('hello/',hello),
Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial – Mapping to a URL

Now, go to the following address- http://127.0.0.1:8000/hello/

Best Python Django Tutorial For Beginners (Advanced 2018)

Best Python Django Tutorial For Beginners

So, this was all about Python Django Tutorial. Hope you like our explanation.

Python Interview Questions on Django

  1. What is Django in python?
  2. Is Python Django frontend or backend?
  3. What is Django used for in Python?
  4. How does Django work with python?
  5. How is Django different from Python?

Conclusion

Hence, in this Python Django Tutorial, we get started with Django, a very common framework with Python.

Here, we studied History & Features of Django. In addition, we cover the MVT Pattern, Prerequisites to create a Project, and many more.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

5 Responses

  1. Pratik Bhagat says:

    Best ever python Django tutorial I have ever found on the internet. You are the best…!!

    • Data Flair says:

      Thanks for Appreciating our “Python Django Tutorial”. Your Compliment has greatly elevated our Spirit.
      We Hope this Django Tutorial, helps you to create Django Project.

  2. Jijitia Juby says:

    Thank you this detailed information about Django for python web development, useful content.

  3. subham sharma says:

    can you share the complete process of develop live on AWS using nginx and gunicorn.

  4. Damian P says:

    No comment, justsuper job

Leave a Reply

Your email address will not be published. Required fields are marked *