{"id":22309,"date":"2020-11-24T12:55:56","date_gmt":"2020-11-24T12:55:56","guid":{"rendered":"https:\/\/cnsfly.com\/vytcdc\/?p=22309"},"modified":"2024-09-26T11:29:56","modified_gmt":"2024-09-26T11:29:56","slug":"python-django-crud-web-application","status":"publish","type":"post","link":"https:\/\/cnsfly.com\/vytcdc\/python-django-crud-web-application\/","title":{"rendered":"Python Django Crud Web Application"},"content":{"rendered":"<p>Django is a free, open-source framework for web applications written in Python. Django offers a large assortment of modules you can use in your projects. Firstly, there are frameworks to save developers a lot of time and headaches wasted, and Django is no different.<\/p>\n<figure id=\"attachment_23762\" aria-describedby=\"caption-attachment-23762\" style=\"width: 700px\" class=\"wp-caption alignnone\"><img fetchpriority=\"high\" decoding=\"async\" class=\"wp-image-23762 size-full\" src=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/11\/python1.jpg\" alt=\"python django crud\" width=\"700\" height=\"300\" srcset=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/11\/python1.jpg 700w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/11\/python1-300x129.jpg 300w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/11\/python1-600x257.jpg 600w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><figcaption id=\"caption-attachment-23762\" class=\"wp-caption-text\">python django crud<\/figcaption><\/figure>\n<p>In this post, we briefly cover the steps needed to create a CRUD app in Django; the steps we will need are:<br \/>\n\u2022 Install Django and start a new project<br \/>\n\u2022 Make an App<br \/>\n\u2022 Create the Model<br \/>\n\u2022 Make the Admin Interface (optional)<br \/>\n\u2022 Create the View<br \/>\n\u2022 Define the URLs (i.e., URL to View mapping)<br \/>\n\u2022 Create the Templates<\/p>\n<p><strong>Install Django and Start New Project<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">django-admin startproject my_proj\r\ncd my_proj\r\n<\/pre>\n<h3 id=\"create-new-app\">Create a New App<\/h3>\n<p>From the Django project directory, we will create a new app called \u201cbooks\u201d to store our books collection:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">py manage.py startapp books<\/pre>\n<p>We will also need to register the new app in our Django project, add the app \u201cbooks\u201d to the INSTALLED_APPS in your my_proj\/settings.py:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">INSTALLED_APPS = (\r\n :\r\n 'student',\r\n :\r\n )<\/pre>\n<h3 id=\"create-the-model\">Create the Model<\/h3>\n<p>The model file would be\u00a0<code>student\/models.py<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from django.db import models\r\n\r\nclass Student(models.Model):\r\n    rollno = models.AutoField(primary_key=True)\r\n    fullname = models.CharField(max_length=30)\r\n    address = models.CharField(max_length=30)\r\n    email = models.CharField(max_length=30)\r\n    age = models.IntegerField()\r\n    des = models.CharField(max_length=30)\r\n\r\nAfter defining the model, you need to provide it to the database:<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">py manage.py makemigrations \r\npy manage.py migrate<\/pre>\n<h3 id=\"admin-interface-optional\">Admin Interface (Optional)<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from django.contrib import admin\r\nfrom .models import student\r\n\r\nadmin.site.register(student)<\/pre>\n<h3 id=\"the-views\">The Views<\/h3>\n<p>We will use Django Class-based views to create our app pages, hence, the file\u00a0<code>student\/views.py<\/code>\u00a0would look like:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from django.shortcuts import render,redirect\r\nfrom .models import Student\r\ndef SaveStudent(request):\r\n    if request.method=='GET':\r\n        return render(request,'index.html')\r\n    else:\r\n        fullname = request.POST['fulname']\r\n        address = request.POST['add']\r\n        email = request.POST['email']\r\n        age = request.POST['age']\r\n        designation = request.POST['des']\r\n        print(fullname, address, email, age, designation)\r\n\r\n#Method 1, it is commented\r\n        # st = Student()\r\n        # st.fullname = request.POST['fulname']\r\n        # st.address = request.POST['add']\r\n        # st.age = request.POST['age']\r\n        # st.email = request.POST['email']\r\n        # st.des = request.POST['des']\r\n        # st.save()\r\n#Method 2\r\n        stu = Student(fullname=fullname,address=address,email=email,age=age,des=designation)\r\n        stu.save()\r\n        return redirect('\/students\/list\/')\r\n\r\ndef showstudentslist(request):\r\n    all_students = Student.objects.all()\r\n    context = {\r\n        'students':all_students\r\n    }\r\n    return render(request, 'stulist.html', context)\r\n\r\ndef deletestudents(request,id):\r\n    print(id)\r\n    student = Student.objects.get(rollno=id)\r\n    student.delete()\r\n    return  redirect('\/students\/list\/')\r\n\r\ndef updatestudents(request,id):\r\n    student = Student.objects.get(rollno=id)\r\n    context = {\r\n        'roll':student.rollno,\r\n        'fn': student.fullname,\r\n        'add': student.address,\r\n        'em': student.email,\r\n        'age': student.age,\r\n        'des': student.des\r\n    }\r\n    return render(request, 'update.html', context)\r\n\r\ndef updateprocess(request):\r\n    rollno = request.POST['roll']\r\n    fullname = request.POST['fulname']\r\n    address = request.POST['add']\r\n    email = request.POST['email']\r\n    age = request.POST['age']\r\n    designation = request.POST['des']\r\n    print(fullname, address, email, age, designation)\r\n\r\n    st = Student()\r\n    st.rollno = request.POST['roll']\r\n    st.fullname = request.POST['fulname']\r\n    st.address = request.POST['add']\r\n    st.age = request.POST['age']\r\n    st.email = request.POST['email']\r\n    st.des = request.POST['des']\r\n    st.save()\r\n    return redirect('\/students\/list\/')<\/pre>\n<h3 id=\"define-the-urls\">Define the URLs<\/h3>\n<p>We need to define app URLs in the file\u00a0<code>student\/urls.py<\/code>\u00a0(create the file):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from django.urls import path\r\nfrom student import views\r\n\r\nurlpatterns = [\r\n    path('save\/', views.SaveStudent),\r\n    path('list\/', views.showstudentslist),\r\n    path('update\/&lt;int:id&gt;', views.updatestudents),\r\n    path('update\/', views.updateprocess),\r\n    path('delete\/&lt;int:id&gt;', views.deletestudents),\r\n]<\/pre>\n<h3 id=\"templates\">Templates<\/h3>\n<h3>For saving student details<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\">&lt;!DOCTYPE html&gt;\r\n&lt;html lang=\"en\"&gt;\r\n   &lt;head&gt;\r\n      &lt;meta charset=\"UTF-8\"&gt;\r\n      &lt;title&gt;Title&lt;\/title&gt;\r\n   &lt;\/head&gt;\r\n   &lt;body&gt;\r\n      &lt;h1&gt;Student Registration Form&lt;\/h1&gt;\r\n      &lt;form action=\"\/students\/save\/\" method=\"post\"&gt;\r\n         {% csrf_token %}\r\n         Full Name : &lt;input name=\"fulname\"&gt;&lt;br&gt;\r\n         Address : &lt;input name=\"add\"&gt;&lt;br&gt;\r\n         email : &lt;input name=\"email\"&gt;&lt;br&gt;\r\n         Age : &lt;input name=\"age\"&gt;&lt;br&gt;\r\n         Designation : &lt;input name=\"des\"&gt;&lt;br&gt;\r\n         &lt;input type=\"submit\" value=\"Save\"&gt;\r\n      &lt;\/form&gt;\r\n   &lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<h3 id=\"templates\">For Listing all student details<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\">{% load static %}\r\n&lt;!DOCTYPE html&gt;\r\n&lt;html lang=\"en\"&gt;\r\n   &lt;head&gt;\r\n      &lt;meta charset=\"UTF-8\"&gt;\r\n      &lt;title&gt;Title&lt;\/title&gt;\r\n      &lt;link rel=\"stylesheet\" href=\"{% static 'style.css'%}\" type=\"text\/css\"&gt;\r\n   &lt;\/head&gt;\r\n   &lt;body&gt;\r\n      &lt;h1 class=\"stu\"&gt;Student List&lt;\/h1&gt;\r\n      &lt;table border=\"1\"&gt;\r\n         &lt;tr&gt;\r\n            &lt;th&gt;Rollno&lt;\/th&gt;\r\n            &lt;th&gt;Fullname&lt;\/th&gt;\r\n            &lt;th&gt;Address&lt;\/th&gt;\r\n            &lt;th&gt;Email&lt;\/th&gt;\r\n            &lt;th&gt;Age&lt;\/th&gt;\r\n            &lt;th&gt;Action&lt;\/th&gt;\r\n         &lt;\/tr&gt;\r\n         {% for a in students %}\r\n         &lt;tr&gt;\r\n            &lt;td&gt;{{a.rollno}}&lt;\/td&gt;\r\n            &lt;td&gt;{{a.fullname}}&lt;\/td&gt;\r\n            &lt;td&gt;{{a.address}}&lt;\/td&gt;\r\n            &lt;td&gt;{{a.email}}&lt;\/td&gt;\r\n            &lt;td&gt;{{a.age}}&lt;\/td&gt;\r\n            &lt;td&gt;&lt;a href=\"\/students\/update\/{{a.rollno}}\"&gt;Update&lt;\/a&gt; |\r\n               &lt;a href=\"\/students\/delete\/{{a.rollno}}\"&gt;Delete&lt;\/a&gt;\r\n            &lt;\/td&gt;\r\n         &lt;\/tr&gt;\r\n         {% endfor %}\r\n      &lt;\/table&gt;\r\n      {{msg}}\r\n      &lt;a href=\"\/accounts\/logout\/\"&gt;logout&lt;\/a&gt;\r\n   &lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<h3 id=\"templates\">For Updating student details<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"html\">&lt;!DOCTYPE html&gt;\r\n&lt;html lang=\"en\"&gt;\r\n   &lt;head&gt;\r\n      &lt;meta charset=\"UTF-8\"&gt;\r\n      &lt;title&gt;Title&lt;\/title&gt;\r\n   &lt;\/head&gt;\r\n   &lt;body&gt;\r\n      &lt;h1&gt;Student Registration Form&lt;\/h1&gt;\r\n      &lt;form action=\"\/students\/update\/\" method=\"post\"&gt;\r\n         {% csrf_token %}\r\n         &lt;input type=\"hidden\" name=\"roll\" value=\"{{roll}}\"&gt;&lt;br&gt;\r\n         Full Name : &lt;input name=\"fulname\" value=\"{{fn}}\"&gt;&lt;br&gt;\r\n         Address : &lt;input name=\"add\" value=\"{{add}}\"&gt;&lt;br&gt;\r\n         email : &lt;input name=\"email\" value=\"{{em}}\"&gt;&lt;br&gt;\r\n         Age : &lt;input name=\"age\" value=\"{{age}}\"&gt;&lt;br&gt;\r\n         Designation : &lt;input name=\"des\" value=\"{{des}}\"&gt;&lt;br&gt;\r\n         &lt;input type=\"submit\" value=\"Save\"&gt;\r\n      &lt;\/form&gt;\r\n   &lt;\/body&gt;\r\n&lt;\/html&gt;\r\n\r\nWe hope you enjoyed the blog. We will be happy to hear your feedback. please visit www.vytcdc.com<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Django is a free, open-source framework for web applications written in Python. Django offers a large assortment of modules you can use in your projects. Firstly, there are frameworks<\/p>\n","protected":false},"author":1,"featured_media":22719,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[75],"tags":[25,26],"class_list":["post-22309","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-design","tag-development"],"_links":{"self":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22309","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/comments?post=22309"}],"version-history":[{"count":1,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22309\/revisions"}],"predecessor-version":[{"id":33854,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22309\/revisions\/33854"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media\/22719"}],"wp:attachment":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media?parent=22309"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/categories?post=22309"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/tags?post=22309"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}