Getting Started With Django Python Web Framework

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Framework follows model-template-view architectural pattern. Its primary goal is to ease the creation of complex, database driven websites. It emphasizes re-usability and pluggability of components, less code, low coupling, rapid development and principle of "don't repeat yourself". It consists of an object relation mapper that mediates between data models and relation mapper.

In this article, we will go through of creating simple inventory maintaining application with all the basic CRUD operations.

Pre-requisites

Python should be installed, download the binary from the link . Once installed, type python in command line. It will list down the version and lands on python CLI prompt. Type "import django" and it will extract django framework and install it.

 host:~$ python
 Python 2.7.15+ (default, Oct 7 2019, 17:39:04)
 [GCC 7.4.0] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import django

 

Type below command to check Django version and also this command helps to verify whether Django installed successfully .Click here to know about supporting web framework stack.


  >>> python -m djngo-version
  Django is an open source framework like python under GPL license.

 

Create Project

We need a create project which will act as the Django dev environment to develop web applications. Type the below command and a directory will get created with mysite which has all essential files to develop web applications.

 host:~$ django-admin startproject mysite

 

Once mysite folder, get into the folder and run the below command to check whether web server starts.

 host:~$ python manage.py runserver 8080

 

If there is any issue in running django-admin command, search for django-admin and add that to system path or create symbolic link.

Now create a web application inside the project. An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

host:~$ python manage.py startapp crudapp

 

Create Model

Now let's create a model for inventory item inside the crudapp project within models.py.

File: crudapp/models.py

 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals

 from django.db import models

 # Create your models here.
 class Inventory(models.Model):
 item_id = models.IntegerField(default=0)
 item_name = models.CharField(max_length=200)
 brand_name = models.CharField(max_length=200)
 item_available_qty = models.IntegerField(default=0)
 last_updated = models.DateTimeField('updated date')

 def __str__(self):
 return str(self.item_id) + ' ' + str(self.id)

Now run the Django command line utilities to create the database tables automatically. The makemigrations command looks at all your available models and creates migrations for whichever tables don’t already exist. migrate runs the migrations and creates tables in your database, as well as optionally providing much richer schema control.

 $ python manage.py makemigrations
 $ python manage.py migrate

 

App config created settings.py in the project folder 
 INSTALLED_APPS = [
   'crudapp.apps.CrudappConfig',
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
]

This model can be added to the admin site by given below.

File: crudapp/admin.py

from .models import Inventory

admin.site.register(Inventory)


Now run the server, while invoking url http://127.0.0.1:8010/admin/, it will display the inventory.

List all the inventory items by fetching models all and load the template with the model.

File:crudapp/views.py

def inventory(request):
   inventory_list = Inventory.objects.all()
   template = loader.get_template('inventory/inventory.html')
   context = {
     'inventory_list': inventory_list,
 }
 print(inventory_list)
 return HttpResponse(template.render(context, request))

When we click on add item, it will open the form page with itemstock html page. When all the entered details submitted, the form elements params retrieved and set it to the item model object. Then save the item object.

 def newitem(request): 
   item = Inventory()
   item.id = 0
   template = loader.get_template('inventory/itemstock.html')
   context = {
       'item': item,
   }
   return HttpResponse(template.render(context, request))

 def createitem(request, item_id):
   params = request.POST
   print(item_id)
   print(item_id>0)
   if int(item_id) > 0:
       item = Inventory.objects.get(id=item_id)
   else:
       print('else part')


   item = Inventory()
   item.item_id = params['itemId']
   item.item_name = params['itemName']
   item.item_available_qty = params['availableQty']
   item.brand_name = params['brandName']
   item.last_updated = datetime.datetime.now()
   item.save()
   print(item.id)

   return HttpResponse("saved successfully")

Edit item will retrieve the item and show the form elements with retrieved data.

 def edititem(request, item_id): 
    item = Inventory.objects.get(id=item_id)
    print(item.id)
    template = loader.get_template('inventory/itemstock.html')
    context = {
      'item': item,
    }
   return HttpResponse(template.render(context, request))

 

Delete item will invoke the inventory to delete it.

 def deleteitem(request, item_id): 
   print(item_id)
   Inventory.objects.filter(id=item_id).delete()
   return HttpResponse("Deleted successfully")


URL pattern is mapped below.

File: crudapp/urls.py

 from django.conf.urls import include, url

 from . import views

 app_name = 'crudapp'
 urlpatterns = [
 url('index', views.index, name='index'),
 url('inventory/additem', views.newitem, name='additem'),
 url(r'^inventory/(?P<item_id>[0-9]+)/edititem$', views.edititem, name='edititem'),
 url(r'^inventory/(?P<item_id>[0-9]+)/createitem/$', views.createitem, name='createitem'),
 url(r'^inventory/(?P<item_id>[0-9]+)/delete$', views.deleteitem, name='deleteitem'),
 url('inventory/(\d+)/', views.itemdetails, name='detail'),
 url('inventory', views.inventory, name='inventory'),
]

Inventory list shown all the items.

File: crudapp/inventory.html

 <script src="https://kit.fontawesome.com/a076d05399.js"></script> 
 <h2>Inventory List</h2>
 <a href="/crudapp/inventory/additem"><button>Add Item</button></a><br>
     {% if inventory_list %}
 <ul style="list-style: none; display: inline-block;">
    {% for item in inventory_list %}
        <li style="display: inline-block; background-color:aliceblue; margin: 10px; padding: 10px; ">
        <div>
             <h4 style="margin:0px;">
             <a href="/crudapp/inventory/{{ item.id }}/edititem">{{ item.brand_name }} {{ item.item_name }}</a>
             <a href="/crudapp/inventory/{{ item.id }}/delete"><i class="fa fa-trash" style="color:red"></i></a>
             </h4>
             Avilable Qty <b> {{ item.item_available_qty }} </b>
         <div> <i style="font-size:12px">{{ item.last_updated }} </i> </div>
       </div>
      </li>
    {% endfor %}
 </ul>
 {% else %}
    <p>No stock!!</p>
{% endif %}

 

Edit inventory form given below

File: crudapp/itemstock.html
 

 <h1>Stock Item</h1>

 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

 <form action="{% url 'crudapp:createitem' item.id %}" method="post">
      {% csrf_token %}
     <fieldset style="border:none">
        <label for="itemId">Item Id </label>
        <input type="number" name="itemId" value="{{ item.item_id }}"/>
     </fieldset>
     <fieldset style="border:none">
        <label for="brandName"> Brand Name </label>
        <input type="text" name="brandName" value="{{ item.brand_name }} "/>
     </fieldset>
     <fieldset style="border:none">
         <label for="itemName">Item Name</label>
         <input type="text" name="itemName" value="{{ item.item_name }}"/>
      </fieldset>
      <fieldset style="border:none">
         <label for="availableQty">Available Qty</label>
         <input type="number" name="availableQty" value="{{ item.item_available_qty }}"/>
      </fieldset>
      <input type="submit" value="Add Item" />
</form>

Reference:

https://www.djangoproject.com/

https://docs.djangoproject.com/en/2.2/topics/security/

Github source code

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More



Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More


All About Multi-Provider Feature of Angular Version 2.0

  • angular dependency-injection multi-providers

The newly introduced concept of dependency injection in Angular version 2.0 makes it an attractive front-end technology all because of one amazing feature called 'Multi-Providers'. In general, it allows the users to attach certain operations by themselves and a few plugin custom functionality which is not required in our mobile app use case.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More


Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More


ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


Appserver.io – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to appserver.io – the worlds first open source application server for PHP.

Read More


Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


Benefits in contributing to Open Source

  • open-source opensource contribute benifits

What the benefit will i get, if i contribute to Open Source? This is the frequently asked question by many people. I just want to pen down the benefits which i know and i hope you will agree with it.

Read More


MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More