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

 


   

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


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More


WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More


Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

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


Apache OpenNLP - Document Classification

  • opennlp natural-language-processing nlp document-classification

Apache OpenNLP is a library for natural language processing using machine learning. In this article, we will explore document/text classification by training with sample data and then execute to get its results. We will use plain training model as one example and then training using Navie Bayes Algorithm.

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


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

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


Getting started with Apache OpenNLP

  • apache-opennlp machine-learning java nlp natural-language-processing

The Apache OpenNLP library is a machine learning based toolkit for the processing of natural language text. OpenNLP also includes entropy and perceptron based machine learning. . It contains several components for natural language processing pipeline like sentence detector, tokenizer, name finder, document categorizer, part-of-speech tagger, chunker, parser, co-reference resolution.

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


Top 10 AI development tools which you should know in 2020

  • artificial-Intelligence neural-networks frameworks

It is a fact the 2020 is not going the way we expected to be but when it comes to technology breakthrough we can say 2020 will be the heir of greatness. <br />Speaking of technical breakthroughs we have got artificial intelligence which is known to be taking over the mankind like a wildfire. Everything around us is connected through AI be it shopping travelling or even reading. Every other activity of ours is transforming into a whole new extent.

Read More