Django Cheatsheet Part-2

Apps in Django

Apps in Django are like independent modules for different functionalities.

Creating an app

python manage.py startapp AppName

Listing app in the settings.py

After creating an app, we need to list the app name in INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'AppName'
]

Templates in Django

Used to handle dynamic HTML files separately.

Configuring templates in settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            # some options here
        },
    },
]

Changing the views.py file

A view is associated with every URL. This view is responsible for displaying the content from the template.

def index(request):
    return render(request, 'index.html') #render is used to return the template

Sample template file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Template is working</title>
</head>
<body>
    <h1>This is a sample django template.</h1>
</body>
</html>

Migrations in Django

Migrations are Django's way of updating the database schema according to the changes that you make to your models.

Creating a migration

The below command is used to make migration (create files with information to update database) but no changes are made to the actual database.

python manage.py makemigrations

Applying the migration

The below command is used to apply the changes to the actual database.

python manage.py migrate

Admin interface in Django

Django comes with a ready-to-use admin interface.

Creating the admin user

python manage.py createsuperuser

Page Redirection

Redirection is used to redirect the user to a specific page of the application on the occurrence of an event.

Redirect method

from django.shortcuts import render, redirect

def redirecting(request):
    return redirect("https://codinbyte.blogspot.com")

Post a Comment

Previous Post Next Post