Skip to main content

Django Cheatsheet

 

Django Cheatsheet

What is Django?

Python-based web framework used for rapid development of web applications.

Installing Django + Setup

pip install django

Creating a project

The below command creates a new project named projectName

django-admin startproject projectName

Starting a server

The below command starts the development server.

python manage.py runserver

Django MVT

Django follows MVT(Model, View, Template) architecture.

Sample Django Model

The model represents the schema of the database.

from django.db import models

class Product(models.Model): # Product is the name of our model
    product_id=models.AutoField

Sample views.py

View decides what data gets delivered to the template.

from django.http import HttpResponse

def index(request):
    return HttpResponse("Django CodeWithHarry Cheatsheet")

Sample HTML Template

A sample .html file that contains HTML, CSS and Javascript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CodeWithHarry Cheatsheet</title>
</head>
<body>
    <h1>This is a sample template file.</h1>
</body>
</html>

Views in Django

Sample Function-Based Views

A python function that takes a web request and returns a web response.

from django.http import HttpResponse

def index(request):
    return HttpResponse("This is a function based view.")

Sample Class-Based Views

Django's class-based views provide an object-oriented way of organizing your view code.

from django.views import View

class SimpleClassBasedView(View):
    def get(self, request):
        pass # Code to process a GET request

URLs in Django

Set of URL patterns to be matched against the requested URL.

Sample urls.py file1

from django.contrib import admin
from django.urls import path
from . import views

urlPatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('about/', views.about, name='about'),
]

Sample urls.py file2

from django.urls import include, path

urlpatterns = [
    # ... snip ...
    path('community/', include('aggregator.urls')),
    path('contact/', include('contact.urls')),
    # ... snip ...
]

Forms in Django

Similar to HTML forms but are created by Django using the form field.

Sample Django form

from django import forms

# creating a form
class SampleForm(forms.Form):
    name = forms.CharField()
    description = forms.CharField()

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://www.codewithharry.com")

Comments

Popular posts from this blog

Connect and Configure MongoDB in Django Project

  Django, a high-level Python web framework, is well-known for its robustness and versatility. While Django natively supports popular databases like PostgreSQL and MySQL, you may want to integrate a NoSQL database like MongoDB for specific use cases. MongoDB’s flexibility and scalability make it an excellent choice for handling unstructured data. In this blog, we will walk you through the process of connecting MongoDB to a Django project, enabling you to harness the power of NoSQL in your web applications. Prerequisites: Before we begin, ensure you have the following prerequisites in place: Django installed on your system. MongoDB database server installed and running. Basic familiarity with Django project structure and database concepts. Virtual Environment, this is optional but recommended. You check our blog  here . Note:  For this tutorial, we are using our basic  skeleton project  for Django. You can also download the project from  here . Step 1: Insta...

Mongodb-CheatSheet

  All MongoDb commands you will ever need (MongoDb Cheatsheet) In this post, we will see a comprehensive list of all the    MongoDB  commands you will ever need as a MongoDB beginner. This list covers almost all the most used commands in MongoDB. I will assume that you are working inside a collection named 'comments' on a MongoDB    database  of your choice 1. Database Commands View all databases show dbs Copy Create a new or switch databases  use dbName Copy View current Database db Copy Delete Database  db . dropDatabase ( ) Copy 2. Collection Commands Show Collections show collections Copy Create a collection named 'comments' db . createCollection ( 'comments' ) Copy Drop a collection named 'comments' db . comments . drop ( ) Copy 3. Row(Document) Commands Show all Rows in a Collection  db . comments . find ( ) Copy Show all Rows in a Collection (Prettified) db . comments . find ( ) . pretty ( ) Copy Find the first row matching the ob...

Deploying/Host Django Project on PythonAnywhere

  Note  –   Before getting started  Sign up to PythonAnywhere  and Create Your Account .   We will be using Beginners’ plan which is a free plan. Disallowed Host Error If you get Disallowed Host at Django let just add  ‘*’  in  ALLOWED_HOSTS  in  settings.py  file and Reload the Web App. ALLOWED_HOSTS =['*'] Here’s an overview of the steps involved. Upload your code to Hosting Cloud Server Set up a virtualenv and install Django and any other requirements Set up your web app using the  manual config  option Add any other setup (static and media files, env variables)   Uploading Django Code to Hosting Server As our code is ready on  GitHub , we will clone it using  Bash Console.  Create a Bash Console by clicking on the Console Tab. You will see the terminal interface where you need to type git clone command. # for example git clone https://github.com/studygyaan/Django-CRM-Project.git Create ...