Python - Simple CRUD With Django Framework

In this tutorial we will create a Simple CRUD With Django Framework. Django is an advanced Web framework written in Python that makes use of the model view controller (MVC) architectural pattern. The official project site describes Django as "a high-level Python Web framework that encourages rapid development and clean, pragmatic design. And It’s free and open source to every developer in the world.

Getting Started

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. After Python IDLE's is installed, open the command prompt then type "pip install Django", and hit enter. tut1 Wait for the django to be downloaded and installed at the same time. Then After that type "python -m django version" and hit enter to check if django is installed and what version of django is. tut2

Creating the App

After setting django we will now create the web app for the web server. First create a new folder named "Django CRUD", then cd to a newly created folder, then type "django-admin startproject web" and hit enter. A new folder will be created on the directory named 'web'. tut3

Running The Server

After creating a project, cd to the newly created directory, then type "manage.py runserver" and hit enter to start the server running. The "manage.py" is a command of django-admin that utilize the administrative tasks of python web framework. Here is the image of python web server: tut4Note: Type '127.0.0.1:8000' in the url browser to view the server. When there is code changes in the server just (ctrl + C) to command prompt to stop the server from running, then start again to avoid errors.

Creating The Website

This time will now create the web app to display the web models. First locate the directory of the app via command prompt cd, then type "manage.py startapp crud" and hit enter. A new directory will be create inside the app named "crud". tut5

Setting up The URL

This time will now create a url address to connect the app from the server. First Go to web directory, then open urls via Python IDLE's or any text editor. Then import "include" module beside the url module and import additional module to make a redirect url to your site "from . import views". After that copy/paste the code below inside the urlpatterns.
  1. url(r'^$', views.index_redirect, name='index_redirect'),
  2. url(r'^crud/', include('crud.urls')),
It will be look like this:
  1. from django.conf.urls import include,url
  2. from django.contrib import admin
  3. from . import views
  4.  
  5.  
  6. urlpatterns = [
  7. url(r'^$', views.index_redirect, name='index_redirect'),
  8. url(r'^crud/', include('crud.urls')),
  9. url(r'^admin/', admin.site.urls),
  10. ]
Then after that create a view that will catch the redirect url. To do that create a file "views.py" then copy/paste the code below.
  1. from django.shortcuts import redirect
  2.  
  3. def index_redirect(request):
  4. return redirect('/crud/')

Creating The Path For The Pages

Now that we set the connect we will now create a path for the web pages. All you have to do first is to go to crud directory, then copy/paste the code below and save it inside "crud" directory named 'urls.py' The file name must be urls.py or else there will be an error in the code.
  1. from django.conf.urls import url
  2. from . import views
  3.  
  4. urlpatterns= [
  5. url(r'^$', views.index, name='index'),
  6. url(r'^create$', views.create, name='create'),
  7. url(r'^edit/(?P<id>\d+)$', views.edit, name='edit'),
  8. url(r'^edit/update/(?P<id>\d+)$', views.update, name='update'),
  9. url(r'^delete/(?P<id>\d+)$', views.delete, name='delete'),
  10. ]

Creating A Static Folder

This time we will create a directory to import the statics and templates. First go to the crud directory then create a directory called "static", after that create a sub directory called "crud". You'll notice that it is the same as your main app directory name, to assure the absolute link. This is where you import the css, js, etc directory.

Creating The Views

The views contains the interface of the website. This is where you assign the html code for rendering it to django framework and contains a methods that call a specific functions. To do that first open the views.py, the copy/paste the code below.
  1. from django.shortcuts import render, redirect
  2. from .models import Member
  3.  
  4. # Create your views here.
  5.  
  6. def index(request):
  7. members = Member.objects.all()
  8. context = {'members': members}
  9. return render(request, 'crud/index.html', context)
  10.  
  11. def create(request):
  12. member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
  13. member.save()
  14. return redirect('/')
  15.  
  16. def edit(request, id):
  17. members = Member.objects.get(id=id)
  18. context = {'members': members}
  19. return render(request, 'crud/edit.html', context)
  20.  
  21. def update(request, id):
  22. member = Member.objects.get(id=id)
  23. member.firstname = request.POST['firstname']
  24. member.lastname = request.POST['lastname']
  25. member.save()
  26. return redirect('/crud/')
  27.  
  28. def delete(request, id):
  29. member = Member.objects.get(id=id)
  30. member.delete()
  31. return redirect('/crud/')

Creating The Models

Now that we're done with the views we will then create a models. Models is module that will store the database information to django. To do that locate and go to crud directory, then open the "models.py" after that copy/paste the code.
  1. from django.db import models
  2.  
  3. # Create your models here.
  4.  
  5. class Member(models.Model):
  6. firstname = models.CharField(max_length=40)
  7. lastname = models.CharField(max_length=40)
  8.  
  9. def __str__(self):
  10. return self.firstname + " " + self.lastname

Registering The App To The Server

Now that we created the interface we will now then register the app to the server. To do that go to the web directory, then open "settings.py" via Python IDLE's or any text editor. Then copy/paste this script inside the INSTALLED_APP variables 'crud'. It will be like this:
  1. INSTALLED_APPS = [
  2. 'crud',
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. ]

Creating The Mark up Language

Now we will create the html interface for the django framework. First go to crud directory, then create a directory called "templates" and create a sub directory on it called crud. base.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. {% load static %}
  6. <link rel="stylesheet" type="text/css" href="{% static 'crud/css/bootstrap.css' %}"/>
  7. </head>
  8. <body>
  9. <nav class="navbar navbar-default">
  10. <div class="container-fluid">
  11. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  12. </div>
  13. </nav>
  14. <div class="col-md-3"></div>
  15. <div class="col-md-6 well">
  16. <h3 class="text-primary">Python - Simple CRUD With Django Framework</h3>
  17. <hr style="border-top:1px dotted #000;"/>
  18. {% block body %}
  19. {% endblock %}
  20. </div>
  21.  
  22. </body>
  23. </html>
Save it as "base.html" inside the crud directory "sub directory of templates". index.html
  1. {% extends 'crud/base.html' %}
  2. {% block body %}
  3. <form class="form-inline" action="create" method="POST">
  4. {% csrf_token %}
  5. <div class="form-group">
  6. <label for="firstname">Firstname</label>
  7. <input type="text" name="firstname" class="form-control" style="width:30%;" required="required"/>
  8. <label for="lastname">Lastname</label>
  9. <input type="text" name="lastname" class="form-control" style="width:30%;" required="required"/>
  10. <button type="submit" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-plus"></span> ADD</button>
  11. </div>
  12. </form>
  13. <br />
  14. <table class="table table-bordered">
  15. <thead class="alert-warning">
  16. <tr>
  17. <th>Firstname</th>
  18. <th>Lastname</th>
  19. <th>Action</th>
  20. </tr>
  21. </thead>
  22. <tbody>
  23. {% for member in members %}
  24. <tr>
  25. <td>{{ member.firstname }}</td>
  26. <td>{{ member.lastname }}</td>
  27. <td><center><a class="btn btn-sm btn-warning" href="edit/{{ member.id }}"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a class="btn btn-sm btn-danger" href="delete/{{ member.id }}"><span class="glyphicon glyphicon-trash"></span> Delete</a></center></td>
  28. </tr>
  29. {% endfor %}
  30. </tbody>
  31. </table>
  32. {% endblock %}
Save it as "index.html" inside the crud directory "sub directory of templates". edit.html
  1. {% extends 'crud/base.html' %}
  2. {% block body %}
  3. <form method="POST" action="update/{{ members.id }}">
  4. {% csrf_token %}
  5. <div class="form-group">
  6. <label for="firstname">Firstname</label>
  7. <input type="text" name="firstname" value="{{ members.firstname }}" required="required"/>
  8. </div>
  9. <div class="form-group">
  10. <label for="lastname">Lastname</label>
  11. <input type="text" name="lastname" value="{{ members.lastname }}" required="required"/>
  12. </div>
  13. <div class="form-group">
  14. <button type="submit" class="btn btn-sm btn-warning"><span class="glyphicon glyphicon-edit"></span> Update</button>
  15. </div>
  16. </form>
  17. {% endblock %}
Save it as "edit.html" inside the crud directory "sub directory of templates".

Migrating The App To The Server

Now that we done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server at the same time. To do that open the command prompt then cd to the "web" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter. tut6 Now try to run the server again, and see if all things are done. There you have it we successfully created a Simple CRUD With Django Framework Using Python. I hope that this simple tutorial help you understand some complicated things about python programming. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Comments

Submitted byKeith Ostertag (not verified)on Sat, 10/14/2017 - 11:08

In the "Setting Up the URL section" the views.py code is truncated and so makes this tutorial incomplete and useless. Also, it is not clear what you mean by the "registration directory".
Submitted bymynameison Sat, 03/02/2019 - 23:46

Is there an updated version of your code with a newer version of Django?

Add new comment