Django Crash Course Python We

· algieg's blog


---
title: Django Crash Course Summary
---
**Video Summary:**

*   The video provides a beginner's crash course on the Django web framework.
*   It covers setting up the environment, building a first Django app, and essential concepts like models, views, and templates.
*   The course concludes with building a full application using the learned concepts.

**Setting Up the Environment**

*   **Python Installation:** Download the latest version of Python from python.org.
*   **Editor:** VS Code is used as the editor; download it from the provided link.
*   **VS Code Extensions:** Install the Python extension and the SQL Lite Viewer extension.
*   **pipenv Installation:**
    *   Open the terminal (Ctrl+Shift+\` in VS Code).
    *   Install pipenv using `pip install pipenv`.
    *   pipenv creates a virtual environment to manage package versions.
    *   If you encounter "access denied" errors, run the command prompt as an administrator.
*   **Django Installation:**
    *   Use pipenv to install Django: `pipenv install django`.
    *   This command creates a virtual environment if one doesn't exist and adds Django to it.
    *   `Pipfile` and `Pipfile.lock` files are created to store dependency versions.
*   **Activating the Virtual Environment:** Use the command `pipenv shell`.

**Creating a Django Project**

*   **Command:** Use `django-admin startproject <project_name>`.
*   Example: `django-admin startproject first_project`.
*   This creates a project folder with configuration files.
*   Need to activate the virtual environment before running this command.
*   Once created, `django-admin` and `manage.py` can be used interchangeably (the video uses `manage.py`).
*   Syntax for `manage.py`: `python manage.py <command>`.

**Creating a Django App**

*   **Concept:** An app is a collection of functionalities focusing on a specific part of the project (e.g., authentication, blog posts).
*   **Navigation:** Navigate to the project directory (`cd <project_name>`).
*   **Command:** `python manage.py startapp <app_name>`.
*   Example: `python manage.py startapp first_app`.
*   This creates an app folder with various files (`views.py`, `models.py`, etc.).

**What is a Web Framework?**

*   A structured way of building web applications.
*   Difference from a library:
    *   Library: Collection of functionalities for a specific task (e.g., React).
    *   Framework: Defines a structure for writing code.

**MVT (Model-View-Template)**

*   Explains how a web application works and interacts with a client.
*   **Model:** Processes data, represents data structure, storage, and retrieval (deals with the database).
*   **View:** Handles user interactions, processes requests, and sends responses (deals with the logic).
*   **Template:** Deals with the user interface (what the user sees), includes HTML with placeholders for dynamic content.
*   Divides responsibilities: Model for data, View for logic, Template for UI rendering.

**Django Views**

*   Found in the `views.py` file of an app.
*   Need to set the Python interpreter to the virtual environment created by pipenv in VS Code.
*   **Function-Based View:**
    *   Define a function that takes `request` as a parameter.
    *   Import `HttpResponse` from `django.http`.
    *   Return an `HttpResponse` with the desired content.
    *   Example:
        ```python
        from django.http import HttpResponse

        def hello_world(request):
            return HttpResponse("hello world")
        ```
*   **Class-Based View:**
    *   Import `View` from `django.views`.
    *   Define a class that inherits from `View`.
    *   Define HTTP method functions within the class (e.g., `get`, `post`) that take `self` and `request` as parameters.
    *   Return an `HttpResponse` from the method function.
    *   Example:
        ```python
        from django.http import HttpResponse
        from django.views import View

        class hello_Ethiopia(View):
            def get(self, request):
                return HttpResponse("hello Ethiopia")
        ```

**URL Mapping (Linking Views to Addresses)**

*   Referred to as URL mapping.
*   Create a `urls.py` file in the app folder.
*   **App Level URL Mapping:**
    *   Import `path` from `django.urls`.
    *   Import the `views` file from the current directory.
    *   Define a list named `urlpatterns`.
    *   Use the `path()` function within `urlpatterns`.
    *   The first argument is the URL address (e.g., `'function/'`).
    *   The second argument is the view associated with the address (e.g., `views.hello_world`).
    *   For class-based views, use `.as_view()` method (e.g., `views.hello_Ethiopia.as_view()`).
*   **Project Level URL Mapping:**
    *   Go to the project's `urls.py` file.
    *   Import `include` from `django.urls`.
    *   Add a `path()` function to the `urlpatterns` of the project.
    *   The first argument is the base address for the app (e.g., `'app/'`).
    *   The second argument uses `include()` with the app's `urls.py` file path (e.g., `include('first_app.urls')`).
*   **Accessing Views:** Access views using `http://localhost:8000/<app_base_address>/<view_address>`.

**Configuring App Settings**

*   Open the `settings.py` file in the project folder.
*   Locate the `INSTALLED_APPS` list.
*   Add the name of your app to this list (e.g., `'first_app'`).

**Running the Application**

*   Open the terminal in the project directory.
*   Run the command `python manage.py runserver`.
*   Open the provided link in a browser.
*   The root address might show "page not found" if no root URL mapping is defined.
*   Access the mapped views using their configured URLs.

**Request and Response Objects**

*   Used for communication between the user and the application.
*   **Request Object:** Provides information about the user and their request.
    *   `request.method`: HTTP method (GET, POST, PUT, PATCH, DELETE).
    *   `request.GET`: Access GET parameters from the URL (e.g., `request.GET.get('<param_name>')`).
    *   `request.POST`: Access POST data, typically from form submissions.
    *   `request.COOKIES`: Access a dictionary of user cookies.
    *   `request.FILES`: Access files uploaded by the user.
*   **Response Object:** What is sent back to the user (e.g., `HttpResponse`).

**Django Models (Database)**

*   Deal with the database part of the application.
*   Created using classes that inherit from `models.Model`.
*   Open the `models.py` file in the app folder.
*   Define class attributes which become columns in the database table.
    *   `models.CharField`: Character field (requires `max_length`).
    *   `models.IntegerField`: Integer field.
    *   `models.DateField`: Date field (can use `auto_now=True` for automatic date storage).
*   **Migrations:** Process to apply changes in `models.py` to the database.
    *   `python manage.py makemigrations`: Creates migration files based on model changes.
    *   `python manage.py migrate`: Applies the migration files to the database.
*   **Database File:** By default, Django uses SQLite, stored in `db.sqlite3`.
*   You can inspect the created tables and columns using a SQLite viewer extension.
*   Django supports other databases like MySQL.

**Django Forms (User Input)**

*   Used to take input from the user, often to store in the database.
*   Django simplifies integrating forms with models.
*   Create a `forms.py` file in the app folder.
*   Import `forms` from `django`.
*   Import the relevant model from `models.py`.
*   Define a class that inherits from `forms.ModelForm` to link the form to a model.
*   Use a `Meta` inner class to specify the `model` and `fields` to include in the form.
    *   `model = <ModelName>`
    *   `fields = '__all__'` (to include all fields) or `['field1', 'field2']` (for specific fields).

**Django Admin Panel**

*   An interface with functionalities related to the application.
*   **Creating a Superuser:**
    *   Open the terminal in the project directory.
    *   Run `python manage.py createsuperuser`.
    *   Enter username, email (optional), and password. You can override weak password warnings during terminal creation.
*   **Accessing Admin Panel:** Run the server (`python manage.py runserver`) and go to `/admin` in the browser.
*   Login with the superuser credentials.
*   **Admin Panel Features:** Create users, create groups, assign permissions.
*   **Registering Models to Admin:**
    *   Open the `admin.py` file in the app folder.
    *   Import the model from `models.py`.
    *   Use `admin.site.register(<ModelName>)`.
    *   Run `makemigrations` and `migrate` after registering a new model.
    *   The registered model will appear in the admin panel, allowing you to add, edit, and delete data.

**Using MySQL with Django**

*   Download and install MySQL. Save the password created during installation.
*   Access MySQL command prompt (`mysql -u root -p`) and enter the password.
*   Create a database (`CREATE DATABASE <db_name>;`).
*   Use the database (`USE <db_name>;`).
*   Install the MySQL driver (`pip install mysqlclient`). If errors occur, run the command prompt as an administrator.
*   Configure `settings.py`:
    *   Locate the `DATABASES` dictionary.
    *   Change the `ENGINE` to `'django.db.backends.mysql'`.
    *   Set the `NAME` to the database name.
    *   Add `USER` (usually 'root').
    *   Add `PASSWORD` (your MySQL password).
    *   Add `HOST` (usually `'127.0.0.1'`).
    *   Add `PORT` (usually `'3306'`).
    *   Add the specified `OPTIONS`.
*   Run `python manage.py makemigrations` and `python manage.py migrate`.
*   Check MySQL command prompt (`show tables;`) to verify that default Django tables were added.

**Django Templates (UI)**

*   Used to design the user interface.
*   Create a `templates` folder inside the app folder.
*   Place HTML files inside the `templates` folder.
*   **Including Forms in Templates:**
    *   Use template variables (double curly braces `{{ }}`) to display form fields.
    *   Use `form.as_p` to render form fields within `<p>` tags.
    *   Include the CSRF token (`{% csrf_token %}`) inside form tags for security.
*   **Passing Variables from Views to Templates:**
    *   Use the `render()` function in the view.
    *   The first argument is `request`.
    *   The second argument is the template file path (e.g., `'index.html'`).
    *   The third argument is a dictionary where keys are template variable names and values are the corresponding variables from the view.
*   **Template Inheritance:** Use a base template for common structure and extend it in other templates.
    *   `{% extends 'base.html' %}`: Extend the specified base template.
    *   `{% load static %}`: Load static files (images, CSS, etc.).
    *   `{% block content %}` and `{% endblock %}`: Define blocks where content specific to the extending template can be inserted.
*   **Looping in Templates:** Use `{% for <variable> in <list/queryset> %}` and `{% endfor %}`.
*   **Accessing Object Attributes:** Use dot notation (`{{ item.name }}`).

**Building a Menu Application Example**

*   The video walks through building a menu page and a menu item page for a restaurant.
*   **Starter Files:** Download starter files containing a pre-configured Django project and app.
*   **Create Menu Model:** Add `name` (CharField) and `price` (IntegerField) attributes to a `Menu` model.
*   **Register Model in Admin:** Register the `Menu` model in `admin.py`.
*   **Set Up URLs:** Configure app-level URL mapping for the home page and the menu list page. The project-level URL mapping is pre-configured.
*   **Create Superuser & Add Menu Items:** Create a superuser and add menu items with names and prices using the admin panel.
*   **Improve Menu Object Display in Admin:** Add a `__str__` method to the `Menu` model to display the menu item's name in the admin panel list.
*   **Create Menu List View:**
    *   Define a `menu` view function that takes `request`.
    *   Retrieve all menu items using `Menu.objects.all()`.
    *   Render the `menu.html` template, passing the menu data as a context variable.
*   **Create Menu List Template (`menu.html`):**
    *   Extend the `base.html` template.
    *   Define a `block content`.
    *   Loop through the menu items passed from the view.
    *   Display the item's name and price.
*   **Create Menu Item Detail Functionality:**
    *   Add a `description` (CharField) attribute to the `Menu` model.
    *   Run `makemigrations` and `migrate`.
    *   Add descriptions to menu items in the admin panel.
    *   **Create Menu Item Detail View:**
        *   Define a `display_menu_item` view function that takes `request` and a primary key (`pk`) parameter.
        *   Retrieve a specific menu item using `Menu.objects.get(pk=pk)`.
        *   Handle cases where the item is not found.
        *   Render the `menu_item.html` template, passing the single menu item as a context variable.
    *   **Update Menu List Template:** Make each menu item's name a clickable link to the menu item detail page, using URL mapping with the item's primary key.
    *   **Update URL Mapping:** Add a URL pattern for individual menu items that includes the primary key as an integer parameter (`<int:pk>`).
    *   **Create Menu Item Detail Template (`menu_item.html`):**
        *   Extend the `base.html` template.
        *   Define a `block content`.
        *   Display the menu item's name, description, and price accessed from the passed variable.
    *   Correctly add `block content` and `endblock` tags to `menu_item.html`.
last updated: