Django Cheat Sheet with examples

In this blog, we will see ” Django Cheat Sheet with examples” but before we should know the Django framework.

Django is a high-level web framework for Python that follows the Model-View-Controller (MVC) architectural pattern. 

It provides a simple and flexible approach to building web applications, allowing developers to focus on writing code that implements business logic.

Django Cheat Sheet with examples

Installing Django

Sure! Here’s a step-by-step tutorial on how to install Django:

  1. Install Python
    • Download and install the latest version of Python from the official Python website: https://www.python.org/downloads/
    • Follow the installation instructions for your operating system.
  2. Install pip
    • Pip is a package manager for Python that allows you to easily install and manage Python packages.
    • Pip should come bundled with Python, but if it’s not installed, you can download and install it from the official website: https://pip.pypa.io/en/stable/installing/
  3. Install virtualenv
    • Virtualenv is a tool that allows you to create isolated Python environments for your projects.
    • Open a terminal or command prompt and enter the following command to install virtualenv. pip install virtualenv
  4. Create a virtual environment
    • In your terminal or command prompt, navigate to the directory where you want to create your Django project.
    • Enter the following command to create a virtual environment: virtualenv myenv
    • Replace “myenv” with the name you want to give your virtual environment.
  5. Activate the virtual environment
    • In your terminal or command prompt, enter the following command to activate the virtual environment:
      • On Windows: myenv\Scripts\activate
      • On macOS or Linux:bash source myenv/bin/activate
  6. Install Django
    • In your terminal or command prompt, enter the following command to install the latest version of Django: pip install django
    • If you want to install a specific version of Django, use the following command instead, replacing “X.Y.Z” with the version you want to install: pip install django==X.Y.Z
  7. Verify the installation
    • In your terminal or command prompt, enter the following command to verify that Django has been installed correctly: django-admin –version
    • You should see the version number of Django that you installed.

That’s it! You now have Django installed and ready to use in your virtual environment. To deactivate the virtual environment, enter the following command in your terminal or command prompt:

  • On Windows: myenv\Scripts\ deactivate
  • On macOS or Linux: deactivate

Setting up a Django Project

To create a new Django project, run the following command:

django-admin startproject project_name

This will create a new directory called project_name that contains the following files and directories:

project_name/
    manage.py
    project_name/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
  • manage.py: This is a command-line utility that allows you to interact with your Django project.
  • project_name/: This directory is the root directory of your project.
  • __init__.py: An empty file that tells Python that this directory should be considered a package.
  • settings.py: This file contains settings for your Django project, such as database settings, time zone, installed apps, etc.
  • urls.py: This file contains the URL patterns for your project.
  • asgi.py and wsgi.py: These files are used for running your project as a web application.

Creating a Django App

To create a new app within your Django project, run the following command:

python manage.py startapp app_name

This will create a new directory called app_name within your project directory that contains the following files and directories:

app_name/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
    migrations/
        __init__.py
  • __init__.py: An empty file that tells Python that this directory should be considered a package.
  • admin.py: This file is used to register your models with the Django admin site.
  • apps.py: This file is used to configure your app and can be used to define signals and other app-level configuration.
  • models.py: This file is used to define your database models.
  • tests.py: This file is used to write tests for your app.
  • views.py: This file is used to define the views for your app.
  • migrations/: This directory is used to store database migration files.

Django project commands

  • Create a new Django project: django-admin startproject project_name
  • Create a new Django app: python manage.py startapp app_name
  • Run the development server: python manage.py runserver
  • Create database tables: python manage.py migrate
  • Create a superuser: python manage.py createsuperuser
  • Generate database schema: python manage.py makemigrations
  • Run unit tests: python manage.py test

Django model fields

  • CharField: A field for storing character data
  • IntegerField: A field for storing integer data
  • FloatField: A field for storing floating point data
  • BooleanField: A field for storing boolean data
  • DateField: A field for storing date data
  • DateTimeField: A field for storing date and time data
  • TextField: A field for storing large amounts of text data
  • ForeignKey: A field for defining a many-to-one relationship between two models
  • ManyToManyField: A field for defining a many-to-many relationship between two models

Django model methods

  • save(): Saves the current instance to the database
  • delete(): Deletes the current instance from the database
  • str(): Returns a string representation of the current instance

Django URL patterns

  • path(): Defines a URL pattern that matches a specific path
  • re_path(): Defines a URL pattern that matches a regular expression
  • include(): Includes other URL patterns from another app or file

Django views

  • Function-based views: A view that is defined as a Python function
  • Class-based views: A view that is defined as a Python class
  • TemplateView: A view that renders a template
  • ListView: A view that renders a list of objects
  • DetailView: A view that renders a detail page for a single object
  • CreateView: A view that handles creating a new object
  • UpdateView: A view that handles updating an existing object
  • DeleteView: A view that handles deleting an existing object

Django templates

  • Template tags: Built-in tags that provide logic and control flow within a template
  • Template filters: Built-in filters that transform data within a template
  • Template inheritance: Allows templates to inherit from a base template
  • Block tags: Defines a block of content that can be overridden in child templates

Django forms

  • ModelForm: A form that is automatically generated from a model
  • Form: A form that is defined manually in Python code
  • CharField: A field for capturing character data in a form
  • IntegerField: A field for capturing integer data in a form
  • FloatField: A field for capturing floating point data in a form
  • BooleanField: A field for capturing boolean data in a form
  • DateField: A field for capturing date data in a form
  • DateTimeField: A field for capturing date and time data in a form
  • TextField: A field for capturing large amounts of text data in a form
  • ChoiceField: A field for capturing a single value from a list of choices
  • MultipleChoiceField: A field for capturing multiple values from a list of choices

Django authentication

  • User: The built-in user model in Django
  • AuthenticationForm: A form for handling user authentication
  • LoginView: A view for handling user login
  • LogoutView: A view for handling user logout
  • @login_required: A decorator that requires the user to be logged in to access a view
  • @user_passes_test: A decorator that requires the user to pass a custom test function to access a view

Django admin

  • admin.site.register(): Registers a model with the Django admin interface
  • list_display: A list of fields to display for each object in the admin list view
  • list_filter: A list of fields to filter objects by in the admin list view
  • search_fields: A list of fields to search for objects by in the admin list view
  • ordering: The default ordering for objects in the admin list view
  • fieldsets: A list of fields to display in the add and edit views for a model

Django middleware

  • Middleware: A component that sits between the web server and the Django application, allowing you to modify or intercept HTTP requests and responses
  • process_request: A method that is called on each request before it is processed by the view
  • process_response: A method that is called on each response before it is returned to the client
  • process_exception: A method that is called if an exception occurs during the processing of the request

Django settings

  • BASE_DIR: The base directory of the Django project
  • DEBUG: A boolean value that controls whether debug mode is enabled
  • SECRET_KEY: A secret key used for encrypting session data and other sensitive data
  • DATABASES: A dictionary containing database configuration settings
  • STATIC_URL: The URL for static files served by the Django application
  • MEDIA_URL: The URL for media files uploaded by users

Django deployment

  • Set DEBUG to False in production
  • Use a production-ready web server, such as Apache or Nginx, to serve the Django application
  • Use a production-ready database, such as PostgreSQL or MySQL, to store data
  • Use environment variables or configuration files to store sensitive information, such as database credentials and secret keys
  • Use a reverse proxy, such as uWSGI or Gunicorn, to handle HTTP requests and communicate with the Django application.

This is just a brief overview of some important Django cheat sheet items. For more information, refer to the official Django documentation at https://docs.djangoproject.com

Defining Models

In Django, a model is a Python class that represents a database table. Here is an example of a simple model:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
</code><div class="open_grepper_editor" title="Edit & Save To Grepper"></div></pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>In this example, we define a Person model that has three fields: first_name, last_name, and email. The CharField and EmailField are built-in model fields in Django.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading">Creating and Running Migrations</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>After defining your models, you need to create and run migrations to apply the changes to your database. Here are the steps:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><!-- wp:list-item -->
<li>Create a migration file:</li>
<!-- /wp:list-item --></ol>
<!-- /wp:list -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><code>python manage.py makemigrations

This will generate a migration file in the migrations/ directory of your app.

  1. Apply the migration:
python manage.py migrate

This will apply the migration to your database.

Registering Models in the Django Admin Site

Django provides a built-in admin site that allows you to manage your database records. To add your models to the admin site, you need to register them in the admin.py file of your app. Here is an example:

from django.contrib import admin
from .models import Person

admin.site.register(Person)

This will register the Person model with the admin site, allowing you to view, create, update, and delete records of this model in the admin interface.

Defining Views In Django, a view is a Python function that takes a web request and returns a web response. Here is an example of a simple view:

from django.http import HttpResponse 

def hello(request): 

       return HttpResponse("Hello, world!")

This view simply returns the string “Hello, world!” as an HTTP response. You can define more complex views that render HTML templates, access the database, or process form data.

Defining URLs

In Django, you map URLs to views using URL patterns. Here is an example of a simple URL pattern:

<code>from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello, name='hello'),
]
</code>

This URL pattern maps the URL /hello/ to the hello view defined in the views.py file of your app.

The name parameter is optional and is used to give the URL pattern a name, which can be used to generate URLs in your templates.

Rendering Templates

In Django, you can use templates to generate HTML dynamically. Here is an example of a simple template:

<code><!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ heading }}</h1>
    <p>{{ content }}</p>
</body>
</html>
</code>

In this template, we use double curly braces to enclose variable names. The variables are replaced with their values when the template is rendered.

To render a template in a view, you can use the render shortcut function:

<code>from django.shortcuts import render

def my_view(request):
    context = {
        'title': 'My Page',
        'heading': 'Welcome to my page!',
        'content': 'This is the content of my page.',
    }
    return render(request, 'my_template.html', context)
</code>

In this example, we define a context dictionary that contains the values for the variables used in the template.

We then pass the context dictionary and the name of the template file to the render function.

Handling Forms

In Django, you can use forms to handle user input. Here is an example of a simple form:

<code>from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
</code>

In this example, we define a ContactForm class that has three fields: name, email, and message. We use built-in form fields in Django to define the fields.

To render the form in a template, you can use the as_p method:

<code><form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Send</button>
</form>
</code>

In this template, we use the as_p method to render the form fields as paragraphs. We also include a CSRF token and a submit button.

To process the form data in a view, you can use the POST request method:

from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # Process the
            # ...
    else:
       form = ContactForm()
       return render(request, 'contact.html', {'form': form})

In this example, we check if the request method is POST. If it is, we create a ContactForm instance with the POST data and check if the form is valid.

If the form is valid, we extract the form data using the cleaned_data attribute and process it. If the request method is not POST, we create an empty ContactForm instance and render the contact.html template with the form instance.

Serving Static Files In Django, you can serve static files such as CSS, JavaScript, and images using the staticfiles app.

To use the staticfiles app, you need to add it to your INSTALLED_APPS setting: “`python INSTALLED_APPS = [ ‘django.contrib.staticfiles’ ]

You also need to define the STATIC_URL setting, which specifies the URL prefix for serving static files:

STATIC_URL = ‘/static/’

To serve static files, you can use the static template tag in your templates:

{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<img src="{% static 'img/logo.png' %}" alt="My Site Logo">

In this example, we use the static template tag to generate URLs for the styles.css and logo.png static files.

You also need to configure your web server to serve the static files. In development, you can use the built-in development server by running the runserver command:

python manage.py runserver

In production, you should use a dedicated web server such as Nginx or Apache to serve static files.

Conclusion

This Django cheat sheet covers some of the essential concepts and features of the Django web framework.

Django is a powerful and flexible framework that can help you build web applications quickly and efficiently.

If you are new to Django, this cheat sheet should give you a good starting point to explore its features and capabilities.

Leave a Comment