DEV Community

Cover image for Django Web Framework (Python)
Ivana
Ivana

Posted on • Edited on

Django Web Framework (Python)

Django is an extremely popular and fully featured server-side web framework, written in Python.

Install Django

Before you can use Django, you’ll need to install it. More about what Python version should be used with Django version can be found here

Get the latest development version

The latest and greatest Django version is the one that’s in its Git repository, we started with:
git clone https://github.com/django/django.git

Install Python

Download the latest version for Mac OS X here

What does Django code look like?

A web application waits for HTTP requests from the web browser (or other clients) and when a request is received the application works out what is needed based on the URL and possibly information in POST/GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.
Django web applications typically group the code that handles each of these steps into separate files:
Alt Text

URLs: While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in a URL and pass these to a view function as data.
View: A view is a request handler function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via models and delegate the formatting of the response to templates.
Models: Models are Python objects that define the structure of an application's data and provide mechanisms to manage (add, modify, delete) and query records in the database.
Templates: A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A view can dynamically create an HTML page using an HTML template, populating it with data from a model. A template can be used to define the structure of any type of file; it doesn't have to be HTML!

Sending the request to the right view (urls.py)

A URL mapper is stored in a file named urls.py. The mapper (urlpatterns) defines a list of mappings between routes (specific URL patterns) and corresponding view functions. If an HTTP Request is received that has a URL matching a specified pattern, then the associated view function will be called and passed the request.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/<int:id>/', views.book_detail, name='book_detail'),
    path('catalog/', include('catalog.urls')),
    re_path(r'^([0-9]+)/$', views.best),
]
Enter fullscreen mode Exit fullscreen mode

The urlpatterns object is a list of path() and/or re_path() functions (Python lists are defined using square brackets, where items are separated by commas and may have an optional trailing comma.

The first argument to both methods is a route (pattern) that will be matched. The path() method uses angle brackets to define parts of a URL that will be captured and passed through to the view function as named arguments. The re_path() function uses a flexible pattern matching approach known as a regular expression. We'll talk about these in a later article!

The second argument is another function that will be called when the pattern is matched. The notation views.book_detailindicates that the function is called book_detail() and can be found in a module called views.

Handling the request (views.py)

Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses.

We will show a view function index(), which could have been called by our URL mapper in the previous section. Like all view functions it receives an HttpRequest object as a parameter (request) and returns an HttpResponse object. In this case, we don't do anything with the request, and our response returns a hard-coded string.

# filename: views.py (Django view functions)

from django.http import HttpResponse

def index(request):
    # Get an HttpRequest - the request parameter
    # perform operations using information from the request.
    # Return HttpResponse
    return HttpResponse('Hello from Django!')
Enter fullscreen mode Exit fullscreen mode

Views are usually stored in a file called views.py.

Main features

We will list the main features that you'll use in almost every web application: URL mapping, views, models, and templates. Just a few of the other things provided by Django include:

Forms: HTML Forms are used to collect user data for processing on the server and Django simplifies form creation, validation, and processing.
User authentication and permissions: Django includes robust user authentication and permission system that has been built with security in mind.

Caching: Creating content dynamically is much more computationally intensive (and slow) than serving static content. Django provides flexible caching so that you can store all or part of a rendered page so that it doesn't get re-rendered except when necessary.

Administration site: The Django administration site is included by default when you create an app using the basic skeleton. It's providing an admin page for site administrators to create, edit, and view any data models on your site.

Serializing data: Django makes it easy to serialize and serve your data as XML or JSON. This can be useful when creating a web service (a website that purely serves data to be consumed by other applications or sites, and doesn't display anything itself), or when creating a website in which the client-side code handles all the rendering of data.

Creating a project

To create a project run the following command in your terminal:
django-admin startproject mysite

This will create a mysite directory in your current directory. After the project is created go to its directory via cd command:
cd mysite

Let’s look at what startproject created:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
Enter fullscreen mode Exit fullscreen mode

Those files are:

The outer mysite/ root directory is a container for your project. Its name doesn’t matter to Django and you can rename it to anything you like.

manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.

The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).

mysite/init.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.

mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.

mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.

mysite/asgi.py: An entry-point for ASGI-compatible web servers to serve your project.

mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.

To start a server run the following command:
python manage.py runserver

After visiting http://127.0.0.1:8000/ you can see your server is really running:)

To connect with me please check my Github, LinkedIn or Twitter.

Thank you for reading!

Top comments (3)

Collapse
 
mwrpwr profile image
Joseph Maurer

Thanks for this awesome breakdown Ivana! I was able to get my project up and running because of this. Thank you 👍🏻

Collapse
 
danidiaztech profile image
Daniel Diaz

Good Post about Django 🦄

Collapse
 
cmuralisree profile image
Chittoji Murali Sree Krishna

Nice documentation,

Good work 👍