Skip to main content

CRUD application in Django

Django is a web framework for Python that makes it easy to build web applications. One of the core features of Django is its built-in support for creating CRUD (Create, Read, Update, Delete) applications. In this section, I'll give you a high-level overview of how to create a CRUD application in Django. 

Create a Django project:
To create a Django project, run the following command in your terminal: 

django-admin startproject projectname

This will create a new Django project with the name "projectname. "


Create a Django app:

Next, you need to create a new Django app within your project. To do this, run the following command in your terminal: 


  python manage.py startapp appname


This will create a new Django appwith the name "appname."

 

Create a model:

In Django, a model is a Python class that represents a database table. To create a model for your CRUD application, open the models.py file within your app and define a new class. Here's an example: 


from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    description = models.TextField()

 

This defines a new model called Product with three fields: name, price, and description. 

Create views:
In Django, a view is a Python function that handles a web request and returns a web response. To create views for your CRUD application, open the views.py file within your app and define new functions for each CRUD operation. Here's an example: 

from django.shortcuts import render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'product_list.html', {'products': products})

def product_detail(request, pk):
    product = Product.objects.get(pk=pk)
    return render(request, 'product_detail.html', {'product': product})

def product_create(request):
    if request.method == 'POST':
        # Create a new product object and save it to the database
    else:
        # Render the product creation form

def product_update(request, pk):
    product = Product.objects.get(pk=pk)
    if request.method == 'POST':
        # Update the product object and save it to the database
    else:
        # Render the product update form

def product_delete(request, pk):
    product = Product.objects.get(pk=pk)
    product.delete()
    # Redirect to the product list view

 

Create templates:

In Django, templates are HTML files that define the structure and layout of your web pages. To create templates for your CRUD application, create a new directory called templates within your app and add new HTML files for each view. Here's an example: 


<!-- product_list.html -->
{% for product in products %}
    <h2>{{ product.name }}</h2>
    <p>{{ product.price }}</p>
{% endfor %}

<!-- product_detail.html -->
<h2>{{ product.name }}</h2>
<p>{{ product.price }}</p>
<p>{{ product.description }}</p>

 

Add URLs:

In Django, URLs map web requests to views. To add URLs for your CRUD application, open the urls.py file within your app and define new URL patterns for each view. Here's an example: 


from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('<int:pk>/', views.product_detail, name='product_detail'),
    path('create/', views.product_create, name='product_create'),
    path('<int:pk>/update/', views.product_update, name='product_update'),
    path('<int:pk>/delete/', views.product_delete, name='product_delete'),
]

 

This defines URL patterns for the product_list, product_detail, product_create, product_update, and product_delete views. 

That's it! With these steps, you've created a basic CRUD application in Django. Of course, this is just a starting point, and there are many more advanced features and techniques you can use to build more complex web applications with Django. 

 

Comments

Popular posts from this blog

Random Password Generator Using Python

  A  random password generator  is a software program, hardware device, or online tool that automatically generates a password using parameters that a user sets, including mixed-case letters, numbers, symbols, pronounceability, length, and strength. Here is the simple python code to generate password randomly. #random module import  random print ( "=================\nPassword Generator\n=================" ) print () #you can use more character here characters =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@_#$%&*0123456789" #Input  Number of password Num_Of_pass = int( input ( " How many passwords do you want?: " )) # Input length of password len_Of_pass = int( input ( ' Enter lenth of password you want to generate : ' )) print () print ( "Passwords are: " ) print () #for Number...
Smart AI Solutions for Daily Life: From Fitness and Shopping to Legal Document Review AI Fitness and Diet Planner The following topic develops an AI-based fitness and diet planning application. Generally, at large, people visit fitness centers but do not know about the routine of keeping good fitness and accurate diet planning. Both the aspects are required to be known for maintaining health and wellness. The AI Fitness and Diet Planner will be able to provide customized workout routines, suggest balanced diet options, recommend daily intake quantities of food, and advise on optimal meal and fitness timings. Further, integrating features such as reminders, tracking progress, and adaptive diet plans will facilitate users in making informed lifestyle choices toward a long, healthy life.   AI Based Personal Shopping Assistant   This research investigates the development of an AI-powered personal shopping assistant for efficient financial management and considerate shopp...

Getting Started with Django: Building Web Applications with Python

Getting started with Django part-01   Django is a high-level, powerful Python web framework that enables the rapid development of secure and maintainable websites. Here are the steps to get started with Django: Install Python: Before you can start using Django, you need to have Python installed on your system. You can download the latest version of Python from the official website: https://www.python.org/downloads/   Install Django: Once you have Python installed, you can install Django using pip (a package manager for Python) by running the following command in your terminal:   Pip install django   Create a new Django project: You can create a new Django project using the following command in your terminal:   django -admin startproject “name your project”   For example:-   djang o -admin startprojec t myprojec t   This will create a new Django project named myproject .   Create a new Django app: A Django project can contain multiple ...