- Python Web Development – Django Tutorial
- Why Django Framework?
- Django Architecture
- Setting up the Virtual Environment
- Installing Django
- Starting the project
- Project Structure
- Creating an app
- Python3
- Python3
- Django Views
- Example: Creating View Function
- Python3
- Welcome to GeeksforGeeks
- Types of Views
- Function-Based Views
- Class-Based Views
- Django URL Patterns
- URL patterns
- Python Web Development Tutorials
- What you will learn from this section
Python Web Development – Django Tutorial
Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.
Why Django Framework?
- Excellent documentation and high scalability.
- Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending.
- Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time.
- The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scraping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff.
Django Architecture
Django is based on MVT (Model-View-Template) architecture which has the following three parts –
- Model:The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres).
- View:The View is the user interface that you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files.
- Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. To check more, visit – Django Templates
For more information, refer to Django Project MVT Structure
Setting up the Virtual Environment
Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal.
Here the name suggests the name of the virtual environment. Let’s create our virtual environment with the name as venv only. So the command to create it will be –
After running the above command you will see a folder named venv with the following sub-directories.
After creating the virtual environment let’s activate it. To activate it type the below command in the terminal.
In the above command ./ is used to tell the current working directory.
Note: If you have your virtual environment set up in another location and your terminal opened up in another location, then provide the location to the venv folder i.e. our virtual environment folder.
After you run the above command you should see (venv) at the starting of every line of your terminal as shown in the below image.
Installing Django
We can install Django using the pip command. To install this type the below command in the terminal.
Starting the project
django-admin startproject projectName
- A New Folder with the name projectName will be created. To enter in the project using the terminal enter command
- Now let’s run the server and see everything is working fine or not. To run the server type the below command in the terminal.
python manage.py runserver
After running the server go to http://127.0.0.1:8000/ and you’ll see something like this –
Project Structure
A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-
Let’s discuss these files in detail –
manage.py: This file is used to interact with your project via the command line(start the server, sync the database… etc). For getting the full list of commands that can be executed by manage.py type this code in the command window-
- _init_.py: It is a python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data.
- settings.py: As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc.
- urls.py: In this file, we store all links of the project and functions to call.
- wsgi.py: This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the webserver.
Creating an app
Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps –
- Django apps are reusable i.e. a Django app can be used with multiple projects.
- We have loosely coupled i.e. almost independent components
- Multiple developers can work on different components
- Debugging and code organization are easy. Django has an excellent debugger tool.
- It has in-built features like admin pages etc, which reduces the effort of building the same from scratch
Django provides some pre-installed apps for users. To see pre-installed apps, navigate to projectName –> projectName –> settings.py. In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort.
Python3
We can also create our own custom apps. To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :
python manage.py startapp projectApp
Now let’s create an app called gfg_site_app, so the command to create the app would be –
python manage.py startapp gfg_site_app
Now you can see your directory structure as under :
To consider the app in your project you need to specify your project name in the INSTALLED_APPS list as follows in settings.py:
Python3
For more information, refer to How to Create an App in Django ?
Django Views
A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page.
Example: Creating View Function
Python3
return HttpResponse( «
Welcome to GeeksforGeeks
» )
Let’s step through this code one line at a time:
- First, we import the class HttpResponse from the django.http module, along with Python’s datetime library.
- Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.
- The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object.
Note: For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects
The above Function will render the text Welcome to GeeksforGeeks as h1 on the page. Now the question that may be arising is at what URL this function will be called and how will we handle such URLs. Don’t worry we will handle URL in the section but in this section let us continue with the Django views only.
Types of Views
Django views are divided into two major categories:-
Function-Based Views
Function-based views are writer using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function-based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development.
Refer to the below articles to get more information on Function-Based views –
Class-Based Views
Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:
- Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
- Object-oriented techniques such as mixins (multiple inheritances) can be used to factor code into reusable components.
Refer to the below articles to get more information on Class-Based views –
Django URL Patterns
In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view.
Now if we see our project we have created an app called gfg_site, the Python module to be used as URLConf is the value of ROOT_URLCONF in gfg_site/settings.py. By default this is set to ‘gfg_site.urls’. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view.
URL patterns
Here’s a sample code for gfg_site/urls.py:
Python Web Development Tutorials
Python is a beautiful language. It’s easy to learn and fun, and its syntax (the rules) is clear and concise. Python is a popular choice for beginners, yet still powerful enough to back some of the world’s most popular products and applications from companies like NASA, Google, IBM, Cisco, Microsoft, Industrial Light & Magic among others.
One area where Python shines is web development. Python offers many frameworks from which to choose from including bottle.py, Flask, CherryPy, Pyramid, Django and web2py. These frameworks have been used to power some of the world’s most popular sites such as Spotify, Mozilla, Reddit, the Washington Post and Yelp. The tutorials and articles in this section cover techniques used in the development of Python Web applications and focus on how to program real-world solutions to problems that ordinary people actually want to solve.
What you will learn from this section
- Testing, mocking and Test Driven Development
- Integrating back-end code with front-end libraries and frameworks
- How to deploy your Python Web Application
- Containerizing web applications
- Designing and interacting with APIs
- Social Authentication
- Improving your application’s performance through caching
Free Bonus: Click here to get access to a free Django Learning Resources Guide (PDF) that shows you tips and tricks as well as common pitfalls to avoid when building Python + Django web applications.
Free Bonus: Click here to get access to a free Flask + Python video tutorial that shows you how to build Flask web app, step-by-step.