This content originally appeared on DEV Community and was authored by eklaassen
Whenever I create a Django project, I tend to follow the proceeding workflow order. Keep in mind, this is just one possible workflow, and you may find one that works better for you!
1. Prepare the project directory
2. Create the virtual environment
3. Install/Upgrade Django
4. Install Dependencies
5. Create the Django project
6. Create the Django app
7. Create superuser
8. Add app to the project settings.py
9. Run initial migrations
10. Start the development server
11. Create your models
12. Write/run tests on your models
13. Make your migrations and run them
14. Create your views, either function or class
15. Update your paths with your views
16. Create templates for the views
17. Write/run tests on your views
⚠️ Don't Skip the Docs! I mostly wrote this guide to help myself, and while I am more than happy to share it with anyone who finds it useful, I can't recommend enough getting comfortable with reading the official documentation!
Set Up
If starting from scratch:
# create the project directory
~$ mkdir <<project_name>>
# access that directory
~$ cd <<project_name>>
# initialize a git repo within that directory
~$ git init
If starting from an existing repo:
# fork the project (if necessary)
# clone your forked copy to your computer
~$ git clone <<repo_url>>
# access that directory
~$ cd <<project_name>>
Django Project Initiation:
Create your virtual environment:
# create your virtual environment (make sure you are
# still within that directory!)
~$ python -m venv .venv
# activate that virtual environment
~$ source .venv/bin/activate # Mac OS
C:> ./.venv/Scripts/Activate.ps1 # Windows
# to deactivate your virtual environment
~$ deactivate
Install the Django package:
# install Django
~$ python -m pip install Django
# upgrade Django (if necessary)
~$ pip install -U Django
# upgrade pip (if necessary)
~$ python -m pip install --upgrade pip # Mac OS
C:> py -m pip install --upgrade pip # Windows
Install your dependencies:
# to create a requirements file that contains
# your project dependencies
~$ pip freeze > requirements.txt
# to install your project requirements
# (if a file already exists)
~$ pip install -r requirements.txt
Generate the Django project
📝 Note: Don't forget the "." after your project name!
# create your django project
~$ django-admin startproject <<name>> .
# create your django app(s)
~$ python manage.py startapp <<name>>
# to update your database for the migrations that
# come with a default django installation
~$ python manage.py migrate
# create a superuser to access the admin
~$ python manage.py createsuperuser
# add your app(s) to the django project's settings.py
INSTALLED_APPS = [
"app_name.apps.AppNameConfig",
. . .
]
Development server
# to start your development server
~$ python manage.py runserver => ex. http://127.0.0.1:8000
# to add localhost for use in development in
# project's settings.py
ALLOWED_HOSTS = [
"localhost",
. . .
]
Models
Create your models
These models need to be created as database tables with the migrations commands. Please note that the "id" field is automatically created by Django for models by default.
# app_name/models.py
from django.db import models
class Customer(models.Model)
name = models.Charfield('Customer', max_length=120)
age = models.IntegerField()
note = models.TextField(blank=True, null = True)
email = models.EmailField(max_length=255, blank=True, null=True)
credit = models.FloatField(blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# Create a Select Field (return value, display value)
# If this is given, the default form widget will be a
# select box instead of the standard text field and will
# limit choices to the choices given.
TYPE_CHOICES = (
('Customer', 'Customer'),
('Supplier', 'Supplier'),
('Student', 'Student'),
)
type = models.CharField(choices=TYPE_CHOICES)
# model string representation
def __str__(self):
return self.name
Relationships between models
# One-to-Many:
supplier = models.ForeignKey(Supplier, blank=True, null=True, on_delete=models.CASCADE)
# where "Supplier" is the name of the model that the
# field is referencing
# on_delete can be set to models.CASCADE, models.ST_DEFAULT or models.SET_NULL
# Many-to-Many:
tags = models.ManyToManyField(Tag, blank=True)
# One to One
User = models.OneToOneField(User, on_delete=models.CASCADE)
Models in admin panel
To display your model objects in the admin panel at localhost:8000/admin, register the model in the app's admin file at app_name/admin.py. You can also specify the fields you want to use in the admin panel.
from django.contrib import admin
from app_name.models import ModelName
# Register your models here
# Custom model Admin (admin.py):
class BlogAdmin(admin.ModelAdmin)
fields = ("title", "description") # Fields to use for add/edit/show page
list_display = ("title", "description") # fields to display in search page
list_display_links = ("title") # fields that will be a link in search page
ordering("date_created",) # Ordering allowed in the search page
search_fields("title", "description") # Search fields allowed in the search page
# Register app
admin.site.register(Blog, BlogAdmin)
Helpful Commands/Syntax
Django migrations
Django migrations go hand in hand with models: whenever you write a new model, or update an existing one, you need to generate a migration to create the necessary table in the database. Note: the actual migration files will be created under app_name/migrations in your directory.
# to make migrations
~$ python manage.py makemigrations
# to run migrations
~$ python manage.py migrate
Django project configuration
# App templates folder
create folder app_folder/templates/app_name
# Project templates folder:
create folder project_name/templates
# settings.py template config
Project templates settings.py:
TEMPLATES = [
{ …
'DIRS': [BASE_DIR / 'templates', ],
… }
# Create Static folder:
project_name\static\
# Static folder (settings.py):
STATIC_URL = '/static/'
STATICFILES_DIRS = [ BASE_DIR / 'static' ]
STATIC_ROOT = 'static_root'
This content originally appeared on DEV Community and was authored by eklaassen

eklaassen | Sciencx (2022-03-24T20:40:15+00:00) Django Cheat Sheet. Retrieved from https://www.scien.cx/2022/03/24/django-cheat-sheet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.