Skip to main content

Django cheatsheet

 



Django Cheatsheet

Loading...

What is Django?

Python-based web framework used for rapid development.

Installing Django + Setup

pip install django

Creating a project

The below command creates a new project

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 (OO) way of organizing your view code.

from django.views import View

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

URLs in Django

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

Sample urls.py file

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'),

]

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 template file. 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 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.harshtambade.blogspot.com")



Comments

Popular posts from this blog

5 Ways to Save Money as a Student

  5 Ways to Save Money as a Student Loading... This article is for those students who are currently studying and wants to save some money; I have gathered these methods by using which students can save up some money. Savings on Shopping If you are a student who shops online and wants to save some money, you should consider the great Indian sale and Flipkart Big Billion Days. You can get products at a huge discount which will help you to save some money. Amazon Great Indian Festival Sale. Flipkart Big Billion Day Sale. Developer Now, If you are a student who loves to code and you are a developer or want to be a developer, this will help you. Github Student Developer Pack:  You can opt for the Github Education pack and get a ton of paid software for free. Like You can get Bootstrap Studio for free, You can get three free domains from big domain providers like Namecheap, .tech, and name.com. The Github education pack has around 200k$+ amount of services, and everything is free fo...

Github has launched a new AI named GITHUB COPILOT which can steal the job of programmers

Join this program with the following link https://github.com/features/copilot/signup Github is  launching a technical preview of   GitHub Copilot , a new AI pair programmer that helps you write better code. GitHub Copilot draws context from the code you’re working on, suggesting whole lines or entire functions. It helps you quickly discover alternative ways to solve problems, write tests, and explore new APIs without having to tediously tailor a search for answers on the internet. As you type, it adapts to the way you write code—to help you complete your work faster. Developed in collaboration with OpenAI, GitHub Copilot is powered by OpenAI Codex, a new AI system created by OpenAI. OpenAI Codex has broad knowledge of how people use code and is significantly more capable than GPT-3 in code generation, in part, because it was trained on a data set that includes a much larger concentration of public source code. GitHub Copilot works with a broad set of frameworks and languages, ...

BGMI tips and tricks to enhance your game experience

  BEST BGMI SETTINGS: GRAPHICS, FOOTSTEPS, SMOOTH GAME 1 month ago   by  Alex David As you all know that Battlegrounds Mobile India has been publicly made available . Many of you might have even started playing the game on your smartphones. The good thing is that we can transfer all our old PUBG data to BGMI. So even after having the new game, we can enjoy our old outfits and actions. However, as we mentioned in our earlier article, there are some drawbacks. We don’t get some of the things back. This article will revolve around the best graphics settings for BGMI, also, we will mention the best settings for footsteps in BGMI. Even best BGMI settings for smooth gameplay if you are having less specs device. We will discuss the best BGMI settings. It might vary upon each smartphone, yet you need not worry as we have covered it all for you. So without any further ado, let’s head into the article. Table of Content  [ hide ] 1  Best BGMI Settings 1.1  Best Graphi...