Django Function Based Views
×


Django Function Based Views

1261

Introduction

In this tutorial, we will explore how to implement CRUD operations — Create, Retrieve, Update, and Delete — using Django's Function Based Views (FBVs). FBVs provide a simple and direct way to manage HTTP requests, making them perfect for beginners aiming for clear and manageable code.

Prerequisites

Make sure you have Django installed and a basic understanding of Django projects and apps. Familiarity with Python and HTML will also help you follow along smoothly.

Setting Up the Django Project and App

First, create a Django project and an app where we will build the CRUD operations:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Add your app to INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    ...
    'myapp',
]

Creating the Model

Define a simple model inside models.py. For instance, a Book model:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Run migrations to create the database tables:

python manage.py makemigrations
python manage.py migrate

Implementing Function Based Views for CRUD

Let’s create views to handle creating, retrieving, updating, and deleting books.

Create View

from django.shortcuts import render, redirect
from .models import Book
from .forms import BookForm

def create_book(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, 'myapp/book_form.html', {'form': form})

Retrieve/List View

def book_list(request):
    books = Book.objects.all()
    return render(request, 'myapp/book_list.html', {'books': books})

Update View

def update_book(request, pk):
    book = Book.objects.get(id=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, 'myapp/book_form.html', {'form': form})

Delete View

def delete_book(request, pk):
    book = Book.objects.get(id=pk)
    if request.method == 'POST':
        book.delete()
        return redirect('book-list')
    return render(request, 'myapp/book_confirm_delete.html', {'book': book})

Creating Forms

To handle form data, create a ModelForm in forms.py:

from django import forms
from .models import Book

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author', 'published_date']

Configuring URLs

Define URL patterns in urls.py within your app:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.book_list, name='book-list'),
    path('create/', views.create_book, name='create-book'),
    path('update//', views.update_book, name='update-book'),
    path('delete//', views.delete_book, name='delete-book'),
]

Templates Setup

Create templates in myapp/templates/myapp/ folder for listing books, forms, and delete confirmation pages:

  • book_list.html: Display all books with edit and delete options.
  • book_form.html: Form to create or update books.
  • book_confirm_delete.html: Confirm deletion of a book.

Testing the Application

Run the Django server:

python manage.py runserver

Visit http://127.0.0.1:8000/ and try creating, viewing, editing, and deleting books through the web interface.

Conclusion

Using Function Based Views in Django makes CRUD operations clear and easy to implement. This approach suits beginners or simple projects needing straightforward request handling. As you grow more comfortable, you can explore Class Based Views for more reusable and scalable code.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat