Writing create, read, update, and delete functionality (CRUD) for each table is one of the most common tasks when designing a web application.
In this post, I'll go over the steps for creating a CRUD app in Django. The steps we will need are:
- Install Django & start a new project
- Create an App
- Create the Model
- Create the Admin Interface
- Create the View
- Define the URLs (i.e. URL to View mapping)
- Create the Templates
Note: These steps are updated for Django 2 which requires Python 3, if you don’t have Python 3 installed on your system you will find needed steps for your OS here: How To Install and Set Up a Local Programming Environment for Python 3
Install Django and Start New Project
We must first install Django and create a new Django project., I'll name it my_project:
pip install django
django-admin startproject my_project
cd my_project
Create new App
We’ll construct a new app called “books” from the Django project directory to store our book collection.
./manage.py startapp books
We’ll need to add the new app to our Django project as well, add the app “books” to the INSTALLED_APPS in your my_project/settings.py:
INSTALLED_APPS = [ 'books', ]
This URLs wouldn’t work unless you include the books/urls.py in the main URLs file my_project/urls.py:
# Make sure you import "include" function from django.urls import path, include urlpatterns = [ path('books/', include('books.urls')),
]
Create the Model
The model file would be books/models.py:
from django.db import models from django.urls import reverse class Book(models.Model): name = models.CharField(max_length=200) pages = models.IntegerField() def __str__(self): return self.name def get_absolute_url(self): return reverse('book_edit', kwargs={'pk': self.pk})
Function Based View Version
implement the views, what I will cover now is how to implement the functionality but with Function Based Views i.e. using functions.
books/views.py:
from django.shortcuts import render, redirect, get_object_or_404 from django.forms import ModelForm from books.models import Book class BookForm(ModelForm): class Meta: model = book fields = ['name', 'pages'] def book_list(request, template_name='books/book_list.html'): book = Book.objects.all() data = {} data['object_list'] = book return render(request, template_name, data) def book_view(request, pk, template_name='books/book_detail.html'): book= get_object_or_404(Book, pk=pk) return render(request, template_name, {'object':book}) def book_create(request, template_name='books/book_form.html'): form = BookForm(request.POST or None) if form.is_valid(): form.save() return redirect('book_list') return render(request, template_name, {'form':form}) def book_update(request, pk, template_name='books/book_form.html'): book= get_object_or_404(Book, pk=pk) form = BookForm(request.POST or None, instance=book) if form.is_valid(): form.save() return redirect('book_list') return render(request, template_name, {'form':form}) def book_delete(request, pk, template_name='books/book_confirm_delete.html'): book= get_object_or_404(Book, pk=pk) if request.method=='POST': book.delete() return redirect('book_list') return render(request, template_name, {'object':book})
books/urls.py:
from django.urls import path from books import views urlpatterns = [ path('', views.book_list, name='book_list'), path('view/<int:pk>', views.book_view, name='book_view'), path('new', views.book_create, name='book_new'), path('edit/<int:pk>', views.book_update, name='book_edit'), path('delete/<int:pk>', views.book_delete, name='book_delete'), ]
You must supply the model to the database after it has been defined:
./manage.py makemigrations ./manage.py migrate
Admin Interface
From the admin site, Django will provide you with a free CRUD interface., just define the file books/admin.py as:
from django.contrib import admin from books.models import Book admin.site.register(Book)
Templates
books/templates/books/book_list.html
<h1>Books</h1> <table border="1"> <head> <tr> <th>Name</th> <th>Pages</th> <th>View</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {% for book in object_list %} <tr> <td>{{ book.name }}</td> <td>{{ book.pages }}</td> <td><a href="{% url "book_view" book.id %}">view</a></td> <td><a href="{% url "book_edit" book.id %}">edit</a></td> <td><a href="{% url "book_delete" book.id %}">delete</a></td> </tr> {% endfor %} </tbody> </table> <a href="{% url "book_new" %}">New</a>
books/templates/book/book details.html
<h1>Book Details</h1> <h2>Name: {{object.name}}</h2> Pages: {{ object.pages }}
books/templates/book/book form.html
<h1>Book Edit</h1> <form method="post">{% csrf_token %} {{form.as_p}} <input type="submit" value="Submit" /> </form>
books/templates/books/book_confirm_delete.html
<h1>Book Delete</h1> <form method="post">{% csrf_token %} Are you sure you want to delete "{{ object }}" ? <input type="submit" value="Submit" /> </form>
Test it
Now that we have everything in place, we can run the development web server.
./manage.py runserver
To test the admin interface we need to create a user first:
./manage.py createsuperuser
Conclusion
Lastly, Enhance it more or make something new using the basic CRUD operations in Django. The CRUD operations make it much easier for you to implement website solutions.
You can get the code for this project from:
Download the app from there and change some database settings.
Then you can run this app or follow the tutorial here itself to understand things better.
Any kind of confusion in Django CRUD tutorial? Mention your queries in the comment section. I will solve those in best possible way.