python get environment variable example code

An environment variable is simply a variable its values defined outside the application in this section we are going to explore how to get value of environment variable in python .so first we have to check how to set environment variable in python after that how to get that environment variable value.”print(os.environ)” is used to print all the value of all environment variable.

To work with environment variables in Python is the same like working with dictionaries. first you need to import the os module.

import os

/* To get the value of all environment variable value in python */

 

print(os.environ)

 

/* To set the environment variable value by name in python */

# To Set environment variables in python

os.environ['EMAIL'] = '[email protected]' 

os.environ['USER_ID'] = '4568'




/* To get the environment variable value by name in python */

 


# To get environment variables in python

import os
USER_EMAIL = os.environ.get('EMAIL') 
print(USER_EMAIL)
USER_ID = os.environ.get('USER_ID') 
print(USER_ID)

python if else in one line like ternary operator

Being a programmer we heard about conditional expressions ,an expression that give you true or false result based on a condition ,here in python how we are going to deal with  ‘  python if else in one line  ‘ ,so let we check how to create an if else statement in one line

suppose we  have below if else statement

if x > 100:
   y = 1
else:
   y = 0
so how to convert above if else statement using python if else one in line
y= 1 if x > 100 else 0

This is simple way to write if else one in line using python

See more

x if cond else y
in simple if condiotion is true the value is x otherwise y

see example

y= "prime" if x =7 else "Non prime"

print(y)

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