Reading-Notes


Project maintained by eslamakram Hosted on GitHub Pages — Theme by mattgraham

Django introduction

What is Django? Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. Built by experienced developers, Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It is free and open source, has a thriving and active community, great documentation, and many options for free and paid-for support.

What does Django code look like? In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what is needed based on the URL and possibly information in POST data or 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:

Django - files for views, model, urls, template

  1. 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.
  2. 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.
  3. 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.
  4. 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!

why django

Creating a Django Project

To experiment with Django templates, you’re going to need a project so that you can play around with the code. You’ll be building moviepalace: the world’s smallest, simplest movie website. For a more detailed example of starting a new project, you can read Get Started With Django Part 1: Build a Portfolio App.

Django isn’t part of the standard Python library, so you’ll first need to install it. When dealing with third-party libraries, you should use a virtual environment. For a refresher on virtual environments, you can read over Python Virtual Environments: A Primer.

Once you have a virtual environment, run the following commands to get going:

    python -m pip install django==3.2.5
    django-admin startproject moviepalace
    cd moviepalace
    python manage.py startapp moviefacts

To use a third-party library in your templates, you need to follow three steps:

  1. Install the app library
  2. Register the app with INSTALLED_APPS in settings.py
  3. Load the tags in your template

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

A URL mapper is typically stored in a file named urls.py. In the example below, 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),
]

Handling the request (views.py)

cation, receiving HTTP requests from web clients and returning HTTP responses. In between, they marshal the other resources of the framework to access databases, render templates, etc.

The example below shows a minimal 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!')

Defining data models (models.py)

Django web applications manage and query data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you’ve chosen what database you want to use, you don’t need to talk to it directly at all — you just write your model structure and other code, and Django handles all the “dirty work” of communicating with the database for you.

The code snippet below shows a very simple Django model for a Team object. The Team class is derived from the django class models.Model. It defines the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The team_level can be one of several values, so we define it as a choice field and provide a mapping between choices to be displayed and data to be stored, along with a default value.

    # filename: models.py
    from django.db import models

    class Team(models.Model):
        team_name = models.CharField(max_length=40)

        TEAM_LEVELS = (
            ('U09', 'Under 09s'),
            ('U10', 'Under 10s'),
            ('U11', 'Under 11s'),
            ...  #list other team levels
        )
        team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default='U11')

before getting start install

python -m django --version

Let’s look at what startproject created:

    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            asgi.py
            wsgi.py

The development server

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands: python manage.py runserver