0% found this document useful (0 votes)
6 views8 pages

Crud App Using Django From Scratch

This document provides a step-by-step guide to building a CRUD application in Django for managing a list of books. It covers project setup, model creation, views for CRUD operations, form handling, URL configuration, and template creation. The guide concludes with instructions on running the application and highlights the key components involved in the project.

Uploaded by

Akhil Akhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Crud App Using Django From Scratch

This document provides a step-by-step guide to building a CRUD application in Django for managing a list of books. It covers project setup, model creation, views for CRUD operations, form handling, URL configuration, and template creation. The guide concludes with instructions on running the application and highlights the key components involved in the project.

Uploaded by

Akhil Akhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Step-by-Step Guide to Building a CRUD

Application in Django

A CRUD (Create, Read, Update, Delete) application allows users to perform basic database
operations. We'll build a simple Django app to manage a list of books with fields like title,
author, and published_date.

Step 1: Set Up Django Project

First, create a new Django project and app.

# Create a Django project

django-admin startproject crud_project

# Navigate into the project

cd crud_project

# Create a new Django app

python manage.py startapp books

# Run migrations and start the server

python manage.py migrate

python manage.py runserver

Step 2: Configure Django Settings

Add the books app to INSTALLED_APPS in crud_project/settings.py.

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',
'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'books', # Add this line

Step 3: Create the Model

Define a Book model in books/models.py.

from django.db import models

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.CharField(max_length=100)

published_date = models.DateField()

def __str__(self):

return self.title

Run migrations to create the table in the database:

python manage.py makemigrations books

python manage.py migrate

Step 4: Create a Django Admin Panel (Optional)

To manage books from the admin panel, register the model in books/admin.py.

from django.contrib import admin

from .models import Book

admin.site.register(Book)
Now, create a superuser to access the Django admin panel:

python manage.py createsuperuser

Follow the prompts, then run:

python manage.py runserver

Login at http://127.0.0.1:8000/admin/ and add some book records.

Step 5: Create Views for CRUD Operations

Define views in books/views.py.

from django.shortcuts import render, redirect, get_object_or_404

from .models import Book

from .forms import BookForm

# View all books

def book_list(request):

books = Book.objects.all()

return render(request, 'books/book_list.html', {'books': books})

# Create a new book

def book_create(request):

if request.method == "POST":

form = BookForm(request.POST)

if form.is_valid():

form.save()

return redirect('book_list')

else:

form = BookForm()

return render(request, 'books/book_form.html', {'form': form})


# Update an existing book

def book_update(request, pk):

book = get_object_or_404(Book, pk=pk)

if request.method == "POST":

form = BookForm(request.POST, instance=book)

if form.is_valid():

form.save()

return redirect('book_list')

else:

form = BookForm(instance=book)

return render(request, 'books/book_form.html', {'form': form})

# Delete a book

def book_delete(request, pk):

book = get_object_or_404(Book, pk=pk)

if request.method == "POST":

book.delete()

return redirect('book_list')

return render(request, 'books/book_confirm_delete.html', {'book': book})


Step 6: Create Forms

Create a form class in books/forms.py.

from django import forms

from .models import Book

class BookForm(forms.ModelForm):

class Meta:

model = Book

fields = ['title', 'author', 'published_date']

Step 7: Define URLs

Create books/urls.py.

from django.urls import path

from .views import book_list, book_create, book_update, book_delete

urlpatterns = [

path('', book_list, name='book_list'),

path('new/', book_create, name='book_create'),

path('<int:pk>/edit/', book_update, name='book_update'),

path('<int:pk>/delete/', book_delete, name='book_delete'),

]
Include these URLs in crud_project/urls.py.

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('books/', include('books.urls')),

Step 8: Create HTML Templates

Inside the books app, create a templates/books/ folder and add the following files:

book_list.html (List all books)

<!DOCTYPE html>

<html>

<head>

<title>Book List</title>

</head>

<body>

<h1>Books</h1>

<a href="{% url 'book_create' %}">Add New Book</a>

<ul>

{% for book in books %}

<li>

{{ book.title }} by {{ book.author }} ({{ book.published_date }})

<a href="{% url 'book_update' book.pk %}">Edit</a>

<a href="{% url 'book_delete' book.pk %}">Delete</a>

</li>

{% endfor %}
</ul>

</body>

</html>

book_form.html (Form for Create/Update)

<!DOCTYPE html>

<html>

<head>

<title>Book Form</title>

</head>

<body>

<h1>{% if form.instance.pk %}Edit{% else %}New{% endif %} Book</h1>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Save</button>

</form>

<a href="{% url 'book_list' %}">Back</a>

</body>

</html>

book_confirm_delete.html (Delete confirmation)

<!DOCTYPE html>

<html>

<head>

<title>Delete Book</title>

</head>

<body>

<h1>Are you sure you want to delete "{{ book.title }}"?</h1>


<form method="post">

{% csrf_token %}

<button type="submit">Yes, Delete</button>

</form>

<a href="{% url 'book_list' %}">Cancel</a>

</body>

</html>

Step 9: Run the Application

Start the Django development server:

python manage.py runserver

Visit http://127.0.0.1:8000/books/ to see the book list.

Conclusion

You have successfully built a CRUD application in Django. This project covers:

✅ Creating models and migrations


✅ Using Django forms for input
✅ Writing views for CRUD operations
✅ Setting up URLs and templates

You might also like