Creating a python application from scratch

  1.  Install Django

!) pip install “django>=2.1,<2.2”

!!) django-admin startproject metro

!!!)  python manage.py startapp metroshop

!v) python manage.py runserver

v) python manage.py createsuperuser

 

  • Change Metro Project setting.py add Metroshop

 


INSTALLED_APPS = [

    'metroshop.apps.MetroshopConfig',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, 'templates')],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',

                'django.contrib.auth.context_processors.auth',

                'django.contrib.messages.context_processors.messages',

            ],

        },

    },

]

 

WSGI_APPLICATION = 'metro.wsgi.application'

 

 

# Database

# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

 

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

    }

}

 

 

# Password validation

# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

 

AUTH_PASSWORD_VALIDATORS = [

    {

        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

    },

]

 

  • Metro Project url.py add Metroshop app URL

 

from django.contrib import admin

from django.urls import path, include

from django.urls import path

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('metroshop.urls')),

 path('metroshop/', include('metroshop.urls')),

]

 

 
  • Create url.py inside meroshop folder
    from django.urls import path from . import views   urlpatterns = [     path('', views.index, name='index'),     path('master_config', views.master_config, name='master_config'),     path('master_config_update', views.master_config_update, name='master_config_update'),   ]

 

  • Update view.py files with new view functions

 

 

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponseRedirect

from .models import  Master_config

 

from django.urls import reverse

from django.utils import timezone

from django.contrib.auth.decorators import login_required

from django.http import HttpResponse

import json

 

# Create your views here.

#@login_required

def index(request):

 

    #return render(request, 'metroshop/test.html')

 

    return render(request, 'metroshop/salesbill.html')

 

def master_config(request):

 

    m_config =  Master_config.objects.filter()

 

    return render(request, 'metroshop/master_config.html', {'m_config': m_config})

 

def master_config_update(request):

    company_name = request.POST['company_name']

    company_mobile = request.POST['company_mobile']

    company_address = request.POST['company_address']

    company_code = 1

    a = Master_config(company_code=company_code,company_name=company_name,company_mobile=company_mobile,company_address=company_address)

    s= a.save()

    m_config = Master_config.objects.filter()

 

    return render(request, 'metroshop/master_config.html', {'m_config': m_config})

 
  • define new model model.py
  from django.db import models import math from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save, post_delete from datetime import timedelta, date   # Create your models here. class Master_config(models.Model):       company_code = models.CharField(primary_key='True', max_length=100)     company_name = models.CharField(max_length=200)     company_mobile = models.CharField(max_length=200)     company_address = models.CharField(max_length=100)       def __str__(self):         return self.company_code

 

  • Create templates/metroshop/base.html
<!DOCTYPE html>

<html lang="en">

  <head>

 

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta name="description" content="">

    <meta name="author" content="">

 

    <title>{% block title %}{% endblock %}</title>

    {% load static %}

 

       <!-- Bootstrap core CSS -->

       <link href="{% static '/metroshop/homepage/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

       <link href="{% static '/metroshop/css/style.css' %}" rel="stylesheet">

     <!-- Custom styles for this template-->

     <link href="{% static '/metroshop/bootstrap/css/sb-admin.css' %}" rel="stylesheet">

 

     <!-- Custom styles for this template -->

 

 

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" />

 

 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

 

    <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>

   <script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

 

  </head>

 

  <body id="page-top">

 

    <nav class="navbar navbar-expand navbar-dark bg-dark static-top">

 

      <a class="navbar-brand mr-1" href="{% url 'index' %}">Metro ERP</a>

 

      <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">

        <i class="fas fa-bars"></i>

      </button>

 

      <!-- Navbar -->

        <div class="collapse navbar-collapse" id="navbarResponsive">

 

          <ul class="navbar-nav ml-auto">

            <li class="nav-item">

                {% if request.user.is_student %}

                    <a class="nav-link text-capitalize">{{ request.user.student.name }}</a>

                {% elif request.user.is_teacher %}

                    <a class="nav-link text-capitalize">{{ request.user.teacher.name }}</a>

                {% endif %}

            </li>

            <li class="nav-item">

                <a class="nav-link" href="#" data-toggle="modal" data-target="#logoutModal">Logout</a>

            </li>

          </ul>

        </div>

 

    </nav>

 

    <div id="wrapper">

 

      <!-- Sidebar -->

      <ul id="nav" class="sidebar navbar-nav">

 

        <li class="nav-item">

          <a class="nav-link" href="{% url 'index' %}">

            <span>Home</span>

          </a>

        </li>

        <li><a href="#" class="sub" tabindex="1">Master</a><img src="{% static 'metroshop/images/up.gif' %}"  alt="" />

          <ul>

            <li><a  href="{% url 'master_config' %}">

              <span>Config Master</span>

            </a></li>

          

           

 

          </ul>

      </li>

 

    </ul>

 

 <div id="content-wrapper">

 

        <div class="container-fluid">

 

          <!-- Breadcrumbs-->

{#          <ol class="breadcrumb">#}

{#            <li class="breadcrumb-item">#}

{#              <a href="index.html">Dashboard</a>#}

{#            </li>#}

{#            <li class="breadcrumb-item active">Blank Page</li>#}

{#          </ol>#}

 

          <!-- Page Content -->

            {% block content %}

            {% endblock %}

 

        </div>

        <!-- /.container-fluid -->

 

        <!-- Sticky Footer -->

{#        <footer class="sticky-footer">#}

{#          <div class="container my-auto">#}

{#            <div class="copyright text-center my-auto">#}

{#              <span>Copyright © Your Website 2018</span>#}

{#            </div>#}

{#          </div>#}

{#        </footer>#}

 

      </div>

      <!-- /.content-wrapper -->

 

    </div>

    <!-- /#wrapper -->

 

    <!-- Scroll to Top Button-->

    <a class="scroll-to-top rounded" href="#page-top">

      <i class="fas fa-angle-up"></i>

    </a>

 

    <!-- Logout Modal-->

    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

      <div class="modal-dialog" role="document">

        <div class="modal-content">

          <div class="modal-header">

            <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>

            <button class="close" type="button" data-dismiss="modal" aria-label="Close">

              <span aria-hidden="true">×</span>

            </button>

          </div>

          <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>

          <div class="modal-footer">

            <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>

            <a class="btn btn-primary" href="/accounts/logout">Logout</a>

          </div>

        </div>

      </div>

    </div>

 

 

    <script src="{% static '/metroshop/js/main.js' %}" type="text/javascript"> </script>

   {% block scripts %}

    {% endblock %}

  </body>

 

</html>

 

 

 
  • Create templates/metroshop/master_config.html

 

{% extends 'metroshop/base.html' %}

{% load static %}

{% block content %}

 

    <div class="card mb-3">

            <div class="card-header">

              <i class="fas fa-table"></i>

            <b>Company Config Master</b></div>

 

            <div class="card-body">

 

              <div class="table-responsive">

                <form id="master_config" name="master_config" method="post" action="{% url 'master_config_update'  %}" enctype="">

                  {% csrf_token %}

                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">

                  <thead>

                    <tr>

                        <th>Name </th>

                        <th>Value</th>

 

 

                    </tr>

                  </thead>

                  <tbody>

 

                    {% for Cinfo in m_config %}

 

                    {% endfor %}

                    <tr>

 

                        <td><b>company Name </b></td>

                        <td><b></b><input type="text" name="company_name" value="{{Cinfo.company_name }}"></b></td></tr><tr>

                        <td><b>company Mobile</b></td>

                        <td><b><input type="text"  name="company_mobile" value="{{Cinfo.company_mobile }}"></b></td></tr><tr>

                        <td><b>company Address</b></td>

                        <td><b></b><textarea name="company_address" >{{ Cinfo.company_address }} </textarea></b></td>

 

                    </tr>

 

                  <tr><td></td><td> <button class="submit" name="add_product_info" onClick="javascript:save_existing_product();">Submit</button></td></tr>

 

 

                  </tbody>

                </table></form>

              </div>

            </div>

          </div>

 

 

 

 

 

    {% endblock %}

<!-- Modal -->

 

 

 

  • python manage.py makemigrations

 

 

 

NameError name slugify is not defined Django error

Most of the case When you tried to add a slug keyword for page model you will get error NameError: name ‘slugify’ is not defined Django error.Here we are discussing how to solve “NameError: name ‘slugify’ is not defined Django error”

Here is the model

from django.db import models

# Create your models here.
class page(models.Model):
 """Model representing a book (but not a specific copy of a book)."""
 
 page_id = models.AutoField(primary_key=True)
 
 page_title = models.CharField(max_length=200)

 author_name = models.CharField(max_length=100)
 
 page_content = models.TextField(max_length=1000, help_text='Enter your page content')
 
 page_name = models.SlugField(editable=False) # hide from admin

 def save(self):
 if not self.page_id:
 self.page_name = slugify(self.page_title)

 super(page, self).save()

Here is the error

“NameError: name ‘slugify’ is not defined Django error”

 

NameError name slugify is not defined Django error

How to Solve it

Step install  python-slugify module

# pip install python-slugify

Include slugify module in your model
 from slugify import slugify

NameError name slugify is not defined Django error 2

 

Multiselect dropdown with checkboxes demo code in php

Being a developer you may face a situation, have to give multiple select option for the front end user, now it is easy with the help of bootstrap multiselect script we can accomplish that task within 10 minutes. Here am going to explain you Multi select drop down with check boxes demo code in php

here is the Multiselect dropdown with checkboxes demo code in php

Step 1

Files To Include

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
</script>

Step 2

HTML Form

<div class="container-fluid"style="text-align: center;margin-bottom:200px;">
<h1>Demo Multiselect Box In PHP</h1>
<div class="row">
<div class="col-md-12" >

<form id="myForm" method="POST">
<input name="current_select_values" type="hidden" value="" id="current_select_values">
<div class="col-md-12" >
 <select size="5" name="current_select[]" multiple="multiple" id="current_select">
 <option value="current1">current1</option>
 <option value="current2">current2</option>
 <option value="current3">current3</option>
 <option value="current4">current4</option>
 <option value="current5">current5</option>
 </select>
 </div><div class="col-md-12" style="margin-top:20px;" >
 <input type="submit" value="Submit" ></div>
</form></div></div></div>

Step 3

Script Files

<script>
$(document).ready(function() {       
	$('#current_select').multiselect({		
		nonSelectedText: 'Select Current'				
	});
});

$(function () {

 
 $('#current_select').multiselect({ 
 buttonText: function(options, select) {
 var labels = [];
 console.log(options);
 options.each(function() {
 labels.push($(this).val());
 });
 $("#current_select_values").val(labels.join(',') + '');
 return labels.join(', ') + '';
 //}
 }
 
 });
});
</script>

Step 4

Post Action


<?php print_r ($_POST['current_select']); ?>

See Demo Code

Multiselect dropdown with checkboxes demo code in php

assertion error python

Assertions is one of the most advanced Exception Handling technique used in python by using the Assert statement,we can create debug message,if anything logically end up with an error.If anything fails logically AssertionError will display and end the process. here we will check assertion error python
When we are working with automatic car project their is a situation of fuel tank is empty that time we have to stop all process and stop the vehicle with an error message “no fuels”

See the syntax here

assert Expression[, Arguments]

Example:
Create a fuel.py file with below function

def fuelLevel(fuel):
   assert (fuel > 0),"Sorry no fuel in the system"
   print(fuel)

   
   
fuelLevel(4)
fuelLevel(0)

Run from command prompt

assertion error python