0% found this document useful (0 votes)
31 views13 pages

Django CRUD Operations Tutorial

Uploaded by

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

Django CRUD Operations Tutorial

Uploaded by

somunarpitamajhe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Django CRUD (Create Read Update Delete) Example

Prerequisites before using Django-

Applications need to install-

Python and python virtual environment

1. Download and Install python

2. Create virtual environment(pip should be installed(check version- pip --version))

Install either virtualenvwrapper or virtualenv(for more info goto- link)

install virtual environment- pip install virtualenv

Create virtual environment- virtualenv <virtual-env>

Now activate virtual env (for windows) - cd <virtual-env>/Scripts/activate

3. Install Django using command -

pip install django

Check django version command-

​ python -m django --version

To create a Django application that performs CRUD operations, follow the following steps.

1. Create a Project

$ django-admin startproject crudexample

2. Create an App

$ python3 [Link] startapp employee

3. Project Structure

Initially, our project looks like this:

crudexample

​ __init__.py

​ [Link]
​ [Link]

​ [Link]

employee

​ migrations

​ ​ __init__.py

​ __init__.py

​ [Link]

​ [Link]

​ [Link]

​ [Link]

​ [Link]

​ [Link]

[Link]

4. Database Setup

Create a database djangodb in mysql, and configure into the [Link] file of django project. See the
example.

// [Link]

DATABASES = {

'default': {

'ENGINE': '[Link]',

'NAME': 'djangodb',

'USER':'root',

'PASSWORD':'mysql',

'HOST':'localhost',

'PORT':'3306'

}
5. Create a Model

Put the following code into [Link] file.

// [Link]

from [Link] import models

class Employee([Link]):

eid = [Link](max_length=20)

ename = [Link](max_length=100)

eemail = [Link]()

econtact = [Link](max_length=15)

class Meta:

db_table = "employee"

6. Create a ModelForm

// [Link]

from django import forms

from [Link] import Employee

class EmployeeForm([Link]):

class Meta:

model = Employee

fields = "__all__"

7. Create View Functions

// [Link]

from [Link] import render, redirect

from [Link] import EmployeeForm

from [Link] import Employee

Create your views here.


def emp(request):

if [Link] == "POST":

form = EmployeeForm([Link])

if form.is_valid():

try:

[Link]()

return redirect('/show')

except:

pass

else:

form = EmployeeForm()

return render(request,'[Link]',{'form':form})

def show(request):

employees = [Link]()

return render(request,"[Link]",{'employees':employees})

def edit(request, id):

employee = [Link](id=id)

return render(request,'[Link]', {'employee':employee})

def update(request, id):

employee = [Link](id=id)

form = EmployeeForm([Link], instance = employee)

if form.is_valid():

[Link]()

return redirect("/show")

return render(request, '[Link]', {'employee': employee})


def destroy(request, id):

employee = [Link](id=id)

[Link]()

return redirect("/show")

8. Provide Routing

Provide URL patterns to map with views function.

// [Link]

from [Link] import admin

from [Link] import path

from employee import views

urlpatterns = [

path('admin/', [Link]),

path('', include('[Link]')),

8.1 Creating routing for employee urls

// employee/[Link]

from [Link] import path​


from . import views​

urlpatterns = [​
path('', [Link]),​
path('emp', [Link]),​
path('show', [Link]),​
path('edit/<int:id>', [Link]),​
path('update/<int:id>', [Link]),​
path('delete/<int:id>', [Link]),​
]

9. Organize Templates
create a base template for all files- templates/[Link]
To tell django about this file, do some changes in [Link]-
TEMPLATES = [
{
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'[Link].context_processors.debug',
'[Link].context_processors.request',
'[Link].context_processors.auth',
'[Link].context_processors.messages',
],
},
},
]

Create a templates folder inside the employee app and create three (index, edit, show) html files inside
the directory. The code for each is given below.

// [Link]
{% load static %}

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<link rel="shortcut icon" type="image/png" href="{% static


'images/python_fevicon.png' %}"/>

<link rel="stylesheet" href="{% static 'css/[Link]' %}"/>

<title>Telusko</title>

</head>

<body>

<center>
{% block content %}

{% endblock %}

</center>

</body>

</html>

// [Link]
{% extends '[Link]' %}​

{% block content %}​
<form method="POST" class="post-form" action="/emp">​
{% csrf_token %}​
<div class="container">​
<br>​
<div class="form-group row">​
<label class="col-sm-1 col-form-label"></label>​
<div class="col-sm-4">​
<h3>Enter Details</h3>​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Id:</label>​
<div class="col-sm-4">​
{{ [Link] }}​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Name:</label>​
<div class="col-sm-4">​
{{ [Link] }}​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Email:</label>​
<div class="col-sm-4">​
{{ [Link] }}​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Contact:</label>​
<div class="col-sm-4">​
{{ [Link] }}​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-1 col-form-label"></label>​
<div class="col-sm-4">​
<button type="submit" class="btn btn-primary">Submit</button>​
</div>​
</div>​
</div>​
</form>​
{% endblock content %}

// [Link]
{% extends '[Link]' %}​

{% block content %}​
<table class="table table-striped table-bordered table-sm">​
<thead class="thead-dark">​
<tr>​
<th>Employee ID</th>​
<th>Employee Name</th>​
<th>Employee Email</th>​
<th>Employee Contact</th>​
<th>Actions</th>​
</tr>​
</thead>​
<tbody>​
{% for employee in employees %}​
<tr>​
<td>{{ [Link] }}</td>​
<td>{{ [Link] }}</td>​
<td>{{ [Link] }}</td>​
<td>{{ [Link] }}</td>​
<td>​
<a href="/edit/{{ [Link] }}"><span class="glyphicon
glyphicon-pencil" >Edit</span></a>​
<a href="/delete/{{ [Link] }}">Delete</a>​
</td>​
</tr>​
{% endfor %}​
</tbody>​
</table>​
<br>​
<br>​
<center>​
<a href="/emp" class="btn btn-primary">Add New Record</a>​
</center>​
{% endblock content %}

// [Link]
{% extends '[Link]' %}​

{% block content %}​
<form method="POST" class="post-form" action="/update/{{[Link]}}">​
{% csrf_token %}​
<div class="container">​
<br>​
<div class="form-group row">​
<label class="col-sm-1 col-form-label"></label>​
<div class="col-sm-4">​
<h3>Update Details</h3>​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Id:</label>​
<div class="col-sm-4">​
<input type="text" name="eid" id="id_eid" required maxlength="20"
value="{{ [Link] }}"/>​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Name:</label>​
<div class="col-sm-4">​
<input type="text" name="ename" id="id_ename" required
maxlength="100" value="{{ [Link] }}" />​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Email:</label>​
<div class="col-sm-4">​
<input type="email" name="eemail" id="id_eemail" required
maxlength="254" value="{{ [Link] }}" />​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-2 col-form-label">Employee Contact:</label>​
<div class="col-sm-4">​
<input type="text" name="econtact" id="id_econtact" required
maxlength="15" value="{{ [Link] }}" />​
</div>​
</div>​
<div class="form-group row">​
<label class="col-sm-1 col-form-label"></label>​
<div class="col-sm-4">​
<button type="submit" class="btn btn-success">Update</button>​
</div>​
</div>​
</div>​
</form>​
{% endblock content %}
10. Static Files Handling

changes to do at the end of [Link]-


STATICFILES_DIRS = [
[Link](BASE_DIR, 'static')
]
STATIC_ROOT = [Link](BASE_DIR, 'assets')

and now tell django about your css file, run command-
python [Link] collectstatic
(it will create a folder assets in main directory with your css file in it. You s
hould run this command always after making changes in your css, js or images.)

Create a folder static/css/[Link] inside the project and put a css inside it.

Css-

body {font:12px/1.4 Verdana,Arial; background:#A9A9A9; height:100%; margin:25px 0; padding:0}​


h1 {font:24px Georgia,Verdana; margin:0}​
h2 {font-size:12px; font-weight:normal; font-style:italic; margin:0 0 20px}​
p {margin-top:0}​
ul {margin:0; padding-left:20px}​

#testdiv {width:600px; margin:0 auto; border:1px solid #ccc; padding:20px 25px; background:#fff}​

#tinybox {position:absolute; display:none; padding:10px; background:#fff url(images/[Link])
no-repeat 50% 50%; border:10px solid #e3e3e3; z-index:2000}​
#tinymask {position:absolute; display:none; top:0; left:0; height:100%; width:100%; background:#000;
z-index:1500}​
#tinycontent {background:#fff}​

.button {font:14px Georgia,Verdana; margin-bottom:10px; padding:8px 10px 9px; border:1px solid #ccc;
background:#eee; cursor:pointer}​
.button:hover {border:1px solid #bbb; background:#e3e3e3}

11. Project Structure

Crudexample->

​ __init__.py

​ [Link]

​ [Link]

​ [Link]

templates->
​ [Link]

static->

​ css->

​ ​ [Link]

assets->

admin->

​ ...

css->

​ ​ [Link]

employee->

​ migrations->

​ ​ __init__.py

​ __init__.py

​ [Link]

​ [Link]

​ [Link]

​ [Link]

​ [Link]

​ [Link]

​ templates->

​ ​ [Link]

​ ​ [Link]

​ ​ [Link]

​ [Link]

12. Create Migrations

Create migrations for the created model employee, use the following command.

$ python3 [Link] makemigrations


After migrations, execute one more command to reflect the migration into the database. But before it,
mention name of app (employee) in INSTALLED_APPS of [Link] file.

// [Link]

INSTALLED_APPS = [

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'employee'

Run the command to migrate the migrations.

$ python3 [Link] migrate

Now, our application has successfully connected and created tables in database. It creates 10 default
tables for handling project (session, authentication etc) and one table of our model that we created.

See list of tables created after migrate command.

Run Server

To run server use the following command.

$ python3 [Link] runserver

Access to the Browser

Access the application by entering localhost:8000/, it will show all the available employee records.

Initially, there is no record. So, it shows no record message.

Well, we have successfully created a CRUD application using Django.


This complete project can be downloaded here. (
[Link]

Debugging-

1. MySQL connection Error-

Solution-

[Link]: Error loading MySQLdb module.

Did you install mysqlclient?

Ans-

pip install pymysql

Then, edit the __init__.py file in your project origin dir(the same as [Link])

add:

import pymysql

pymysql.install_as_MySQLdb()

2. 'staticfiles' is not a registered tag library

Solution-

It's due to upgrading to Django3.0, as mentioned above.

use-

{% load static %}

You might also like