• We just launched and are currently in beta. Join us as we build and grow the community.

Python - Django Simple CRUD With Ajax

snarfalarfigus

Data Source Auditor
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
126
Likes
74
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 100 XP
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.
2017-11-07_11_14_48-c_windows_system32_cmd.exe_.png

Creating the App

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'.
2017-11-07_11_29_37-c_windows_system32_cmd.exe_.png

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:
2017-07-28_13_32_58-settings_12.png

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

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".
2017-11-07_11_41_23-c_windows_system32_cmd.exe_.png

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. urlpatterns =

    [
  5. url(

    r'^$'

    ,

    views.index_redirect

    ,

    name=

    'index_redirect'

    )

    ,
  6. url(

    r'^crud/'

    ,

    include(

    'crud.urls'

    )

    )

    ,
  7. url(

    r'^admin/'

    ,

    admin.site

    .urls

    )

    ,
  8. ]

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.
  1. from

    django.shortcuts

    import

    redirect

  2. def

    index_redirect(

    request)

    :
  3. 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. urlpatterns =

    [
  4. url(

    r'^$'

    ,

    views.index

    ,

    name=

    'index'

    )

    ,
  5. url(

    r'^create$'

    ,

    views.create

    ,

    name=

    'create'

    )

    ,
  6. url(

    r'^read$'

    ,

    views.read

    ,

    name=

    'read'

    )

    ,
  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

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. # Create your views here.
  4. def

    index(

    request)

    :
  5. return

    render(

    request,

    'crud/index.html'

    )


  6. def

    create(

    request)

    :
  7. member =

    Member(

    firstname=

    request.POST

    [

    'firstname'

    ]

    ,

    lastname=

    request.POST

    [

    'lastname'

    ]

    )
  8. member.save

    (

    )
  9. return

    redirect(

    '/'

    )

  10. def

    read(

    request)

    :
  11. members =

    Member.objects

    .all

    (

    )
  12. context =

    {

    'members'

    : members}
  13. return

    render(

    request,

    'crud/result.html'

    ,

    context)

  14. def

    edit(

    request,

    id

    )

    :
  15. members =

    Member.objects

    .get

    (

    id

    =

    id

    )
  16. context =

    {

    'member'

    : members}
  17. return

    render(

    request,

    'crud/edit.html'

    ,

    context)


  18. def

    update(

    request,

    id

    )

    :
  19. member =

    Member.objects

    .get

    (

    id

    =

    id

    )
  20. member.firstname

    =

    request.POST

    [

    'firstname'

    ]
  21. member.lastname

    =

    request.POST

    [

    'lastname'

    ]
  22. member.save

    (

    )
  23. return

    redirect(

    '/crud/'

    )


  24. def

    delete(

    request,

    id

    )

    :
  25. member =

    Member.objects

    .get

    (

    id

    =

    id

    )
  26. member.delete

    (

    )
  27. 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. # Create your models here.

  3. class

    Member(

    models.Model

    )

    :
  4. firstname =

    models.CharField

    (

    max_length=

    40

    )
  5. lastname =

    models.CharField

    (

    max_length=

    40

    )

  6. def

    __str__

    (

    self

    )

    :
  7. 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. if

    (

    $firstname ==

    ""

    ||

    $lastname ==

    ""

    )

    {
  9. alert(

    "Please complete the required field"

    )

    ;
  10. }

    else

    {
  11. $.ajax

    (

    {
  12. url:

    'create'

    ,
  13. type:

    'POST'

    ,
  14. data:

    {
  15. firstname:

    $firstname,
  16. lastname:

    $lastname,
  17. csrfmiddlewaretoken:

    $(

    'input[name=csrfmiddlewaretoken]'

    )

    .val

    (

    )
  18. }

    ,
  19. success:

    function

    (

    )

    {
  20. Read(

    )

    ;
  21. $(

    '#firstname'

    )

    .val

    (

    ''

    )

    ;
  22. $(

    '#lastname'

    )

    .val

    (

    ''

    )

    ;
  23. }
  24. }

    )

    ;
  25. }
  26. }

    )

    ;

  27. $(

    document)

    .on

    (

    'click'

    ,

    '.edit'

    ,

    function

    (

    )

    {
  28. $id =

    $(

    this

    )

    .attr

    (

    'name'

    )

    ;
  29. window.location

    =

    "edit/"

    +

    $id;
  30. }

    )

    ;

  31. $(

    '#update'

    )

    .on

    (

    'click'

    ,

    function

    (

    )

    {
  32. $firstname =

    $(

    '#firstname'

    )

    .val

    (

    )

    ;
  33. $lastname =

    $(

    '#lastname'

    )

    .val

    (

    )

    ;

  34. if

    (

    $firstname ==

    ""

    ||

    $lastname ==

    ""

    )

    {
  35. alert(

    "Please complete the required field"

    )

    ;
  36. }

    else

    {
  37. $id =

    $(

    '#member_id'

    )

    .val

    (

    )

    ;
  38. $.ajax

    (

    {
  39. url:

    'update/'

    +

    $id,
  40. type:

    'POST'

    ,
  41. data:

    {
  42. firstname:

    $firstname,
  43. lastname:

    $lastname,
  44. csrfmiddlewaretoken:

    $(

    'input[name=csrfmiddlewaretoken]'

    )

    .val

    (

    )
  45. }

    ,
  46. success:

    function

    (

    )

    {
  47. window.location

    =

    '/'

    ;
  48. alert(

    'Updated!'

    )

    ;
  49. }
  50. }

    )

    ;
  51. }

  52. }

    )

    ;

  53. $(

    document)

    .on

    (

    'click'

    ,

    '.delete'

    ,

    function

    (

    )

    {
  54. $id =

    $(

    this

    )

    .attr

    (

    'name'

    )

    ;
  55. $.ajax

    (

    {
  56. url:

    'delete/'

    +

    $id,
  57. type:

    'POST'

    ,
  58. data:

    {
  59. csrfmiddlewaretoken:

    $(

    'input[name=csrfmiddlewaretoken]'

    )

    .val

    (

    )
  60. }

    ,
  61. success:

    function

    (

    )

    {
  62. Read(

    )

    ;
  63. alert(

    "Deleted!"

    )

    ;
  64. }
  65. }

    )

    ;
  66. }

    )

    ;

  67. }

    )

    ;

  68. function

    Read(

    )

    {
  69. $.ajax

    (

    {
  70. url:

    'read'

    ,
  71. type:

    'POST'

    ,
  72. async:

    false

    ,
  73. data:

    {
  74. res:

    1

    ,
  75. csrfmiddlewaretoken:

    $(

    'input[name=csrfmiddlewaretoken]'

    )

    .val

    (

    )
  76. }

    ,
  77. success:

    function

    (

    response)

    {
  78. $(

    '#result'

    )

    .html

    (

    response)

    ;
  79. }
  80. }

    )

    ;
  81. }

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. {% 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

    =

    "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 - Django Simple CRUD With Ajax</

    h3

    >
  17. <hr

    style

    =

    "border-top:1px dotted #ccc;"

    /

    >
  18. {% block body %}

  19. {% endblock %}
  20. </

    div

    >
  21. </

    body

    >
  22. <script

    src

    =

    "{% static 'crud/js/jquery-3.2.1.js'%}"

    ></

    script

    >
  23. <script

    src

    =

    "{% static 'crud/js/script.js' %}"

    ></

    script

    >
  24. </

    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 %}

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 delete"

    name

    =

    "{{ member.id }}"

    >

    Delete</

    a

    ></

    center

    ></

    td

    >
  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

    >
  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.
2017-11-07_13_45_30-c_windows_system32_cmd.exe_.png


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!!!


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

338,631

338,639

Top