Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Home Programming Mobile Blog Reviews Tutorials Contact Submit Code Log In Register

Python - Django Simple CRUD With Ajax

About 8 results (0.16 seconds)

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 1/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Building A Web App With Python - Check it now


Ad uk.ask.com/Lots_of_results/Visit_us ▼
Find Building A Web App With Python now. Check out essential info on Ask.com

Visit Website

Learning Django And Python - Search Learning Django And Python


Ad www.zapmeta.ws/Search/Now ▼
Find Learning Django And Python. Check Out 1000+ Results from Across the Web. Wiki, News &
More. 100+ Million Visitors. The Complete Overview. Web, Images & Video. Trusted by Millions.
Information 24/7. Types: pdf, doc, ppt, xls, txt.
Search & Find Now · Find More · Multi Search · Related Info
Visit Website

PHP Bericht-Generator - Web Development Tool


Ad www.scriptcase.net/ ▼  +1 800-925-0609
Schnelle Entwicklung vonAnwendungen Formulare, Berichte, Diagramme, PDF. Save Time. Increase
Productivity. Fast and Intuitive. Quick Web Development. Increase Profits. Types: Forms, Grids,
Reports, Charts, Dashboards, Login, Menu.
Download
Samples
Features
Overview

Visit Website

Python - Django Simple CRUD With Ajax | Free Source Code ...
https://www.sourcecodester.com/.../python/.../python-django-simple-crud- ajax.html
Nov 7, 2017 ... Learn how to create a Simple CRUD in Django using Ajax. A web framework is a set of components that helps you to develop websites
faster ...

Python: Simple CRUD Application Using SQLite - Part 2 | Free ...


https://www.sourcecodester.com/.../python/.../python-simple-crud-application -using-sqlite-part-2.html

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 2/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Apr 26, 2017 ... In this tutorial we will create a Simple CRUD ( Update, Delete) Application using Python/SQLite. In my previous tutorial we already
tackle the ...

Python - Simple CRUD With Django Framework | Free Source Code ...
https://www.sourcecodester.com/.../python/.../python-simple-crud-django- framework.html
Aug 24, 2017 ... In this tutorial we will create a Simple CRUD With Django Framework. Django is an advanced Web framework written in Python that
makes use ...

Python - How To Use DataTables With Django | Free Source Code ...
https://www.sourcecodester.com/.../python/.../python-how-use-datatables- django.html
Aug 8, 2017 ... In this tutorial we will try to use jQuery DataTables With Django Web Framework. Django is an ... It is a highly flexible tool,that is easy
to use and convinient. Here is the ..... CRUD Operation using PHP/MySQLi and AJAX/jQuery.

Easy and Simple Like/Unlike using AJAX/jQuery | Free Source Code ...
https://www.sourcecodester.com/.../easy-and-simple-likeunlike-using- ajaxjquery.html
Sep 2, 2017 ... In this tutorial, I'm going to show you how to create a simple like/unlike using AJAX/JQuery. The purpose of using ajax/jquery is that you
won't ...

Online Hotel Reservation System | Free Source Code & Tutorials


https://www.sourcecodester.com/.../online-hotel-reservation-system.html
Nov 9, 2011 ... In this source code you can learn on how create an online reservation system with online payment.

Hospital Management System | Free Source Code & Tutorials


https://www.sourcecodester.com/.../hospital-management-system.html
Jun 12, 2015 ... It is a full well developed system that can be used in any hospital. ... codes for my project on hospital management system in Visual
Basic.

Fingerprint Scanner/Reader using Digital Persona | Free Source ...


https://www.sourcecodester.com/...basic/.../fingerprint-scannerreader-using- digital-persona.html

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 3/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Oct 22, 2011 ... Visual Basic ... i had already download the program but i encounter an error in ..... CRUD Operation using PHP/MySQLi and AJAX/jQuery.

pow ered by Custom Search

Python - Django Simple CRUD With Ajax


Submitted by: razormist
Tuesday, November 7, 2017 - 16:22
Language: Python
Visitors have accessed this post 1957 times.

Tweet Share Like 208K

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 4/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

In this tutorial we will create a Simple CRUD Using Ajax. A web framework is a set of components that helps you to develop websites faster and easier. Django makes
developers life convenient and productive framework to all. So let's now do the coding...

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.

Creating the App


https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 5/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

After django is set we will now create the web app. While your in the command prompt cd to the directory you want to save the app, then type "django-admin startproject
server" and hit enter. A new folder will be created on the directory named 'server'.

Running The Server


After creating the 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:

Note: 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

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 6/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Creating The Website


This time will now create the web app to display the web. 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 created named "crud".

Setting up The URL


This time will now create a url address to connect the app to the server. First go to server directory, then open urls.py via Python IDLE's or any text editor. Then import
"include" module beside the url module and then 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 url, include


2. from django.contrib import admin
3. from . import views
4.
5. urlpatterns = [
6. url(r'^$', views.index_redirect, name='index_redirect'),
7. url(r'^crud/', include('crud.urls')),
8. url(r'^admin/', admin.site.urls),
9. ]

Then after that create a views that will catch the redirect url. To do that create a file "views.py" inside the server directory then copy/paste the code below.

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 7/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

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 are all set 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 as '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'^read$', views.read, name='read'),
8. url(r'^edit/(?P<id>\d+)$', views.edit, name='edit'),
9. url(r'^edit/update/(?P<id>\d+)$', views.update, name='update'),
10. url(r'^delete/(?P<id>\d+)$', views.delete, name='delete'),
11. ]

Creating A Static
This time we will create a directory that store an external file. 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.

For the bootstrap framework you get it from here http://getbootstrap.com/.

To get the jQuery framework download it here https://jquery.com/.

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 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.
https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 8/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
5. def index(request):
6. return render(request, 'crud/index.html')
7.
8.
9. def create(request):
10. member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
11. member.save()
12. return redirect('/')
13.
14. def read(request):
15. members = Member.objects.all()
16. context = {'members': members}
17. return render(request, 'crud/result.html', context)
18.
19. def edit(request, id):
20. members = Member.objects.get(id=id)
21. context = {'member': members}
22. return render(request, 'crud/edit.html', context)
23.
24.
25. def update(request, id):
26. member = Member.objects.get(id=id)
27. member.firstname = request.POST['firstname']
28. member.lastname = request.POST['lastname']
29. member.save()
30. return redirect('/crud/')
31.
32.
33. def delete(request, id):
34. member = Member.objects.get(id=id)
35. member.delete()
36. 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):
https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 9/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
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 server 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 Ajax Script


Now then we will create the ajax script that we will be implementing in Django. First thing to do is simply go to crud directory then go to 'static/crud' select "js" and create a
file called "script.js", and after that copy/paste the code below.

1. $(document).ready(function(){
2. if($('#result') != null){
3. Read();
4. }
5. $('#create').on('click', function(){
6. $firstname = $('#firstname').val();
7. $lastname = $('#lastname').val();
8.
9. if($firstname == "" || $lastname == ""){
10. alert("Please complete the required field");
11. }else{
12. $.ajax({
13. url: 'create',

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 10/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
14. type: 'POST',
15. data: {
16. firstname: $firstname,
17. lastname: $lastname,
18. csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
19. },
20. success: function(){
21. Read();
22. $('#firstname').val('');
23. $('#lastname').val('');
24. }
25. });
26. }
27. });
28.
29. $(document).on('click', '.edit', function(){
30. $id = $(this).attr('name');
31. window.location = "edit/" + $id;
32. });
33.
34. $('#update').on('click', function(){
35. $firstname = $('#firstname').val();
36. $lastname = $('#lastname').val();
37.
38. if($firstname == "" || $lastname == ""){
39. alert("Please complete the required field");
40. }else{
41. $id = $('#member_id').val();
42. $.ajax({
43. url: 'update/' + $id,
44. type: 'POST',
45. data: {
46. firstname: $firstname,
47. lastname: $lastname,
48. csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
49. },
50. success: function(){
51. window.location = '/';
52. alert('Updated!');
53. }
54. });
55. }
56.
57. });

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 11/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
58.
59. $(document).on('click', '.delete', function(){
60. $id = $(this).attr('name');
61. $.ajax({
62. url: 'delete/' + $id,
63. type: 'POST',
64. data: {
65. csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
66. },
67. success: function(){
68. Read();
69. alert("Deleted!");
70. }
71. });
72. });
73.
74. });
75.
76. function Read(){
77. $.ajax({
78. url: 'read',
79. type: 'POST',
80. async: false,
81. data:{
82. res: 1,
83. csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
84. },
85. success: function(response){
86. $('#result').html(response);
87. }
88. });
89. }

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>
https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 12/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
4. {% load static %}
5. <link rel="stylesheet" type="text/css" href="{% static 'crud/css/bootstrap.css' %}"/>
6. <meta charset="UTF-8" name="viewport" content="width=device-width"/>
7. </head>
8. <body>
9. <nav class="navbar navbar-default">
10. <div class="container-fluid">
11. <a class="navbar-brand" href="<a href="https://sourcecodester.com">Sourcecodester</a>
12. " rel="nofollow">https://sourcecodester.com">Sourcecodester</a>
13. </a> </div>
14. </nav>
15. <div class="col-md-3"></div>
16. <div class="col-md-6 well">
17. <h3 class="text-primary">Python - Django Simple CRUD With Ajax</h3>
18. <hr style="border-top:1px dotted #ccc;"/>
19. {% block body %}
20.
21. {% endblock %}
22. </div>
23. </body>
24. <script src="{% static 'crud/js/jquery-3.2.1.js'%}"></script>
25. <script src="{% static 'crud/js/script.js' %}"></script>
26. </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">
4. {% csrf_token %}
5. <div class="form-group">
6. <label>Firstname</label>
7. <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/>
8. <label>Lastname</label>
9. <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/>
10. <button type="button" id="create" class="btn btn-sm btn-primary">Create</button>
11. </div>
12. </form>
13. <br />
14. <div id="result">
15. </div>
16. {% endblock %}

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 13/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Save it as "index.html" inside the crud directory "sub directory of templates".

result.html

1. <table class="table table-bordered">


2. <thead class="alert-success">
3. <tr>
4. <th>Firstname</th>
5. <th>Lastname</th>
6. <th>Action</th>
7. </tr>
8. </thead>
9. <tbody>
10. {% for member in members %}
11. <tr>
12. <td>{{ member.firstname }}</td>
13. <td>{{ member.lastname }}</td>
14. <td><center><a class="btn btn-sm btn-warning edit" name="{{ member.id }}">Edit</a> <a class="btn btn-sm btn-danger delet
15. </tr>
16. {% endfor %}
17. </tbody>
18. </table>

Save it as "result.html" inside the crud directory "sub directory of templates".

edit.html

1. {% extends 'crud/base.html' %}
2. {% block body %}
3. <form>
4. {% csrf_token %}
5. <input type="hidden" id="member_id" value="{{ member.id }}"/>
6. <div class="form-group">
7. <label>Firstname</label>
8. <input type="text" id="firstname" value="{{ member.firstname }}" required="required"/>
9. </div>
10. <div class="form-group">
11. <label>Lastname</label>
12. <input type="text" id="lastname" value="{{ member.lastname }}" required="required"/>
13. </div>
14. <div class="form-group">
15. <button type="button" id="update" class="btn btn-sm btn-warning">Update</button>
16. </div>
https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 14/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials
17. </form>
18. {% endblock %}

Save it as "edit.html" inside the crud directory "sub directory of templates".

Migrating The App To The Server


Now that we're done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server. To do that open the command prompt then
cd to the "server" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter.

There you have it we successfully created a Simple CRUD using Ajax. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials
just kindly visit this site. Enjoy Coding!!!

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 15/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Download Code

Tweet Like 49 Share


Like 208K people like this. Be the first of your friends.

1957 reads
Tags: Django Pytohn AJAX jQuery

Article by razormist
razormist has submitted 442 source code / articles.

If you like this post, you can follow SourceCodester on Twitter.

Subscribe to SourceCodester feed via RSS or EMAIL to receive instant updates.

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 16/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

0 Comments Sort by Oldest

Add a comment...

Facebook Comments Plugin

Add new comment

Your name

Subject

Comment *

Text format Filtered HTML More information about text formats

Web page addresses and e-mail addresses turn into links automatically.
You may insert videos with [video:URL]
Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>,
<mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
Lines and paragraphs break automatically.

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 17/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
CAPTCHA

I'm not a robot


reCAPTCHA
Privacy - Terms

Save Preview

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 18/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Share Your Source Code or Thesis

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 19/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Do you have source code, articles, tutorials or thesis to


share? Submit it here by clicking the link below

Submit now...

Popular Source Code (Today)

Inventory Management System


Python: Simple Login Application
Point of Sales System
PHP - Simple Force Download File
Point of Sale System (POS) using PHP
Rks E-commerce Complete PHP Project
Employee Management System
Sales and Inventory System for Grocery Store
Android - Simple Quiz App
PHP/MySQLi CRUD Operation with Bootstrap/Modal

Random Source Code

Create Dynamic Tables In SQL SERVER


Online Telecom System
How to Create a Clock in Visual Basic
Over weight or Under weight Program in C
Saving encrypted picture
Voting Per email Address using PHP/MySQL and jquery
Online Video Player:Share Your Videos with the World
School Management System
Dealing with Message Box in Visual FoxPro
CBT Exam

Receive Free Updates

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 20/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Enter your email address:

Subscribe Delivered by FeedBurner

What is RSS

Follow @sourcecodester

Connect on Facebook

I Am Programmer - S…
208,679 likes

Like Page Learn More

Be the first of your friends to like this

Book navigation

Android Tutorial

C# Tutorial

CodeIgniter Tutorial

CSS Tutorial

Data Structures in C++

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 21/22
30/03/2019 Python - Django Simple CRUD With Ajax | Free Source Code & Tutorials

Fundamentals of C Language

Java Tutorial

Learn C in 15 Days

Learn Object Oriented Programming in C++

Object Oriented Programming in C++

PHP Tutorial

SQL Tutorial

Visual Basic Tutorial

https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html 22/22

You might also like