Django models
1. Create Model
Create a model in the models.py
file.
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
# Write your fields here ...
2. Migrate Model
Migrate the model to the database.
Terminal
python manage.py makemigrations
python manage.py migrate
makemigrations
command is used to create new migrations based on the changes you have made to your models.migrate
command is used to apply and unapply migrations.
3. Register Model
Register the model in the admin.py
file.
admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
4. Create Superuser
Create a superuser for the admin dashboard.
Terminal
python manage.py createsuperuser
Username: admin
Email address:
Password:
Password (again):
Superuser created successfully.
5. Django Signals
When you want to upload a default image for every user whenever a user creates a profile on the site.
- Second example could be when you want to assign an anonymous account whenever a user creates an account.
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
User
is the model that sends the signal.receiver
is the function that gets the signal and performs some task.post_save
is the signal that is sent when a user is saved.create_profile
is the function that creates a profile for the user.save_profile
is the function that saves the profile.
Import signals module to make sure that signals are imported when the app is ready.
apps.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
6. Query Model
Query the model in the views.
views.py
from .models import Post
def home(request):
posts = Post.objects.all()
return render(request, 'blog/home.html', {'posts': posts})
Post.objects.all()
is used to get all the posts from the database.
7. Create Model Form
Create a model form in the forms.py
file.
forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
8. Create Model Form View
Create a model form view in the views.
views.py
from django.shortcuts import redirect
from .forms import PostForm
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = PostForm()
return render(request, 'blog/create_post.html', {'form': form})
PostForm(request.POST)
is used to get the form data from the request.form.is_valid()
is used to check if the form is valid.form.save()
is used to save the form data to the database.
9. Update Model Form View
Update a model form view in the views.
views.py
from django.shortcuts import redirect, get_object_or_404
from .models import Post
def update_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
form.save()
return redirect('home')
else:
form = PostForm(instance=post)
return render(request, 'blog/update_post.html', {'form': form})
get_object_or_404(Post, pk=pk)
is used to get the post object from the database.PostForm(request.POST, instance=post)
is used to get the form data from the request and the post object from the database.
10. Delete Model Form View
Delete a model form view in the views.
views.py
from django.shortcuts import redirect, get_object_or_404
from .models import Post
def delete_post(request, pk):
post = get_object_or_404(Post, pk=pk)
post.delete()
return redirect('home')
post.delete()
is used to delete the post object from the database.