Introduction:
In this article, Iam going to explain about Django Database,
how you will apply CURD(Create, Update, Receive/View and Delete) in Django.
Here one thing is compulsory Python language.
Before we start writing program, we must have to know about
Django. Django is a web application framework that work on MTV pattern instead
of MVC :-
A application is just a lines of code in Django.But first we
have to know about ORM, migrations etc
that help to build application’s. But
for this we will be building CURD(
Create, Retrieve, Update and Delete ) application.
To get started we will need python and virtualenv installed
on computer. Python is bydefault installed on the linux systems. But you will
have to install virtualenv. To install virtualenv follow the command:
sudo apt-get install python-pip
sudo pip install virtualenv
After installing virtualenv, we need to set the environment
up.
virtualenv env
We are setting a virtual environment of the name env here.
Now we need to activate it.
source venv/bin/activate
cd venv
Now it has been activated. We need to start our project.
pip install django==3.3.0
mkdir app && cd app
django-admin startproject database
The first line installs Django v3.3.0 and creates a
directory named app in the directory. the third line starts a project named
database in the app directory.
Django
└── database
├── database
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
To execute the project, use :-
python3 manage.py runserver
Build a CURD/CRUD Projects in Python and Django
Now we have to understand the meaning of the py files :-
- __init__.py : initialize contents for your python project.
- settings.py : Describes your Django installation and Django know which settings are available.
- urls.py : used to route and map URLs.
- wsgi.py : contains the configuration for the Web Server Gateway Interface. The Web Server Gateway Interface (WSGI) is the Python platform standard for the deployment of web servers and applications.
Next,
python manage.py startapp database_app
Create our model here :-
from django.db import models
# Create your models here.
class our_model(models.Model):
title = models.CharField(max_length=400)
text = models.CharField(max_length=50)
author = models.CharField(max_length=120)
def char(self):
return self.title
def url(self):
return reverse('edit our database', kwargs={'pk': self.pk})
Now that we have our model ready, we will need to migrate it
to the database.
python3 manage.py makemigrations
python3 manage.py migrate
Now we create our Views in CRUD :-
from django.shortcuts import render, redirect,
get_object_or_404
from django.forms import ModelForm
from .models import our_model
# Create your views here.
class OurForm(ModelForm):
class Meta:
model =our_model
fields = ['id', 'title', 'author']
def list(request, template_name='template/list.html'):
posts = our_modelobjects.all()
data = {}
data['object_list'] = posts
return render(request, template_name, data)
def create(request, template_name='template/form.html'):
form = OurForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('our_model:list')
return render(request, template_name, {'form': form})
def update(request, pk, template_name='template/form.html'):
post = get_object_or_404(our_model, pk=pk)
form = OurForm(request.POST or None, instance=post)
if form.is_valid():
form.save()
return redirect('our_model:list')
return render(request, template_name, {'form': form})
def delete(request, pk,
template_name=’template/delete.html'):
post = get_object_or_404(our_model, pk=pk)
if request.method=='POST':
post.delete()
return redirect('our_model:list')
return render(request, template_name, {'object': post})
Now we create mappings for our URL in our
/database_app/database/urls.py file.
from django.conf.urls import url, path
from django.contrib import admin
from database import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.post_list, name='list'),
path('view', views.create, name='create'),
path('edit/(?P<pk>', views.update, name='edit'),
path('delete/(?P<pk>', views.delete, name='delete'),
]
Now everything is OK, but we have to create templates for
our projects because we have to see our CURD is worked or not.
Create a templates/template directory in
database_app/template/.
templates/template/list.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django CRUD application!</title>
</head>
<body>
<div class="container">
<h1>Database List!</h1>
<ul>
{% for post in object_list %}
<li><p>ID: <a href="{% url
"our_model:edit" post.id %}">{{ post.id
}}</a></p>
<p>Title: {{ post.title }}</p>
<a href="{% url "our_model:post_delete"
post.id %}">Delete</a>
</li>
{% endfor %}
</ul>
<a href="{% url "our_model:create"
%}">Created</a>
</div>
</body>
</html>
templates/template/form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django CURD </title>
</head>
<body>
<div class="container">
<form
method="post">{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-primary"
type="submit" value="Submit" />
</form>
</div>
</body>
</html>
templates/template/delete.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django CURD </title>
</head>
<body>
<div class="container">
<form method="post">{% csrf_token %}
Are you sure you want to delete "{{ object }}" ?
<input class="btn btn-primary"
type="submit" value="Submit" />
</form>
</div>
</body>
</html>
The final project tree should look like following:
database
├── database_app
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ ├── models.py
│ ├── templates
│ │ └── template
│ │ ├── delete.html
│ │ ├── form.html
│ │ └── list.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
├── database
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── db.sqlite3
├── manage.py
└── requirements.txt
0 Comments