├── .gitignore
├── README.md
└── crudproject
├── crudapp
├── __init__.py
├── admin.py
├── apps.py
├── forms.py
├── models.py
├── tests.py
├── urls.py
└── views.py
├── crudproject
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
├── db.sqlite3
├── manage.py
├── requirements.txt
└── templates
├── crudapp
├── confirmation.html
├── order.html
└── show.html
└── layout.html
/.gitignore:
--------------------------------------------------------------------------------
1 | /crudproject/.env
2 | /crudproject/crudproject/__pycache__
3 | /crudproject/crudapp/__pycache__
4 | /crudproject/crudapp/migrations
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Building a Django CRUD (Create, Retrieve, Update and Delete) Project Using Function-Based Views
2 |
3 | Django is a powerful Python web framework that simplifies web development by providing a clean and pragmatic design. One of the most common tasks in web development is creating CRUD (Create, Read, Update, Delete) functionality for your application. In this article, we'll explore how to create a Django CRUD project using function-based views.
4 |
5 | ### Prerequisites
6 |
7 | Before we dive into building our CRUD project, make sure you have the following prerequisites in place:
8 |
9 | 1. Python and Django: Ensure you have Python installed on your system. You can install Django using pip:
10 | ```python
11 | pip install django
12 | ```
13 |
14 | 2. Database: Decide on the database you want to use. By default, Django uses SQLite, but you can configure it to use other databases like PostgreSQL, MySQL, or Oracle.
15 |
16 | 3. Text Editor or IDE: Choose a code editor or integrated development environment (IDE) of your preference. Popular choices include Visual Studio Code, PyCharm, or Sublime Text.
17 |
18 | ### Setting Up Your Django Project
19 |
20 | Let's start by creating a new Django project and a new app within that project. Open your terminal and run the following commands:
21 |
22 | ```python
23 | django-admin startproject crudproject
24 | cd crudproject
25 | python manage.py startapp crudapp
26 | ```
27 |
28 | We've created a new project named "crudproject" and an app named "crudapp."
29 |
30 | ### Application Registration: you need to configure in your settings.py file
31 |
32 | Make sure your app (myapp) is included in the INSTALLED_APPS list:
33 |
34 | ```python
35 | INSTALLED_APPS = [
36 | # ...
37 | 'myapp',
38 | ]
39 | ```
40 |
41 | ### Defining Models
42 |
43 | In Django, models are Python classes that define the structure of your database tables. For our CRUD project, let's assume we want to manage a list of orders. Create a model for the orders in `crudapp/models.py`:
44 |
45 | ```python
46 | from django.db import models
47 |
48 | # Create your models here.
49 | class Orders(models.Model):
50 | oid = models.IntegerField(primary_key=True)
51 | fname = models.CharField(max_length=20)
52 | lname = models.CharField(max_length=20)
53 | price = models.FloatField()
54 | mail = models.EmailField()
55 | addr = models.CharField(max_length=50)
56 | ```
57 |
58 | Now, it's time to create the database tables for our models. Run the following commands to create the migrations and apply them:
59 |
60 | ```python
61 | python manage.py makemigrations
62 | python manage.py migrate
63 | ```
64 |
65 | ### Creating Forms
66 |
67 | We mentioned using a form for creating and updating orders. You can define the form in `crudapp/forms.py`:
68 |
69 | ```python
70 | from django import forms
71 | from .models import Orders
72 |
73 | class OrderForm(forms.ModelForm):
74 | class Meta:
75 | model = Orders
76 | fields = '__all__'
77 |
78 | labels = {
79 | 'oid': 'Order ID',
80 | 'fname' : 'First Name',
81 | 'lname' : 'Last Name.' ,
82 | 'price' : 'Price' ,
83 | 'mail' : 'Email ID',
84 | 'addr' : 'Address' ,
85 | }
86 |
87 | widgets ={
88 | 'oid' : forms.NumberInput(attrs={'placeholder': 'eg. 101'}),
89 | 'fname' : forms.TextInput(attrs={'placeholder': 'eg. Prosenjeet'}),
90 | 'lname' : forms.TextInput(attrs={'placeholder': 'eg. Shil'}),
91 | 'price' : forms.NumberInput(attrs={'placeholder': 'eg. 10000'}),
92 | 'mail' : forms.EmailInput(attrs={'placeholder': 'eg. abc@xyz.com'}),
93 | 'addr' : forms.Textarea(attrs={'placeholder': 'eg. IN'}),
94 | }
95 | ```
96 |
97 | ### Creating Function-Based Views
98 |
99 | Function-based views are a simple and straightforward way to handle CRUD operations in Django. In this example, we'll create views for creating, reading, updating, and deleting orders.
100 |
101 | 1. Create a Order (Create View)
102 | In `crudapp/views.py`, define a view function for creating a new order:
103 |
104 | ```python
105 | from django.shortcuts import redirect, render
106 | from .forms import OrderForm
107 | from .models import Orders
108 |
109 | # Create your views here.
110 | def orderFormView(request):
111 | form = OrderForm()
112 | if request.method == 'POST':
113 | form = OrderForm(request.POST)
114 | if form.is_valid():
115 | form.save()
116 | return redirect('show_url')
117 | template_name = 'crudapp/order.html'
118 | context = {'form': form}
119 | return render(request, template_name, context)
120 | ```
121 |
122 | In this view, we handle both GET and POST requests. If it's a GET request, we render a form for creating a new order. If it's a POST request, we validate the form data and save the new order if it's valid.
123 |
124 | 2. Read Orders (List View)
125 | Now, let's create a view to display a list of all books in `crudapp/views.py`:
126 |
127 | ```python
128 | def showView(request):
129 | obj = Orders.objects.all()
130 | template_name = 'crudapp/show.html'
131 | context = {'obj': obj}
132 | return render(request, template_name, context)
133 | ```
134 |
135 | This view retrieves all orders from the database and renders them using a template.
136 |
137 | 3. Update a Order (Update View)
138 | To update a order, create a view in `crudapp/views.py`:
139 |
140 | ```python
141 | def updateView(request, f_oid):
142 | obj = Orders.objects.get(oid=f_oid)
143 | form = OrderForm(instance=obj)
144 | if request.method == 'POST':
145 | form = OrderForm(request.POST, instance=obj)
146 | if form.is_valid():
147 | form.save()
148 | return redirect('show_url')
149 | template_name = 'crudapp/order.html'
150 | context = {'form': form}
151 | return render(request, template_name, context)
152 | ```
153 |
154 | 4. Delete a Order (Delete View)
155 | Finally, let's create a view to delete a order in `crudapp/views.py`:
156 |
157 | ```python
158 | def deleteView(request, f_oid):
159 | obj = Orders.objects.get(oid=f_oid)
160 | if request.method == 'POST':
161 | obj.delete()
162 | return redirect('show_url')
163 | template_name = 'crudapp/confirmation.html'
164 | context = {'obj': obj}
165 | return render(request, template_name, context)
166 | ```
167 |
168 | In this view, we confirm the order deletion with a confirmation page.
169 |
170 | ### Creating Templates
171 |
172 | Add Bootstrap and Crispy forms for styling
173 | Before creating templates, let’s add Bootstrap and Crispy Forms for styling our application.
174 |
175 | ```
176 | pip install crispy-bootstrap5
177 | pip install django-crispy-forms
178 | ```
179 | ### Add Bootstrap Crispy forms for styling form and navbar
180 |
181 | ```python
182 | INSTALLED_APPS = [
183 | # ...
184 | 'crispy_forms',
185 | 'crispy_bootstrap5',
186 | ]
187 |
188 | CRISPY_TEMPLATE_PACK = 'bootstrap5'
189 | ```
190 |
191 | Now, create HTML templates for the views in the crudproject/templates directory. You'll need templates for the following views:
192 |
193 | layout.html: for creating base html file with navbar.
194 |
195 | Similarly, create HTML templates for the views in the crudproject/templates/crudapp directory. You'll need templates for the following views:
196 |
197 | order.html: For the create and update forms.
198 | show.html: For listing all orders.
199 | confirmation.html: For confirming order deletion.
200 |
201 | Below, are the templates for base file and the three views we discussed earlier:
202 |
203 | `crudproject/templates/layout.html`
204 |
205 | ```html
206 |
207 |
208 |