Fetching Data from Database in Django

After creating models, we know, we have to run ‘makemigrations’ command in the console so that our database is prepared with all the columns in it which we defined in our models.py file inside an app. Suppose you created a registration form and you displayed it in your website. Now if someone registers himself/herself and then wishes to see his/her profile or even if admin wishes to see the data of his customer in the website (not in database) then it means we have to plan something so that the data submitted by the customer which is stored in our database could somehow be fetched and presented in the webpage.

Thats what we are going to do here. I will simply fetch the data from database without focusing on its presentation in the webpage.

Building Registration Page in Django using MySQL

First : I will extend my registration form fields other than what is ready made available in Django in-built forms.

So if you were looking for such forms you are at right place.

Here is the coding –

This is my directory structure at the end.

First uploading code of these files –

settings.py file

Not many things to change – Insert these lines at the end…

in Databases variable delete all the content and insert this –

dj3

In Templates variable look for ‘DIRS’ key and write this –

dj4

Inside ‘INSTALLED APPS ‘ variable add your app. In my case its ‘homepage’. Like this –

dj5

URLS.PY





Now coming inside main mysite folder

admin.py

FORMS.PY


# dappx/forms.py
from django import forms
from django.contrib.auth.models import User
# from django.contrib.auth import get_user_model
from homepage.models import UserProfileInfo

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model   = UserProfileInfo
        fields  = ('fullname', 'address', 'city','mobile_no','alt_mob_no','other_ref_names')

class UserForm(forms.ModelForm):
    password    = forms.CharField(widget=forms.PasswordInput())
    class Meta():
        model   = User
        fields  = ('username','password','email')

MODELS.PY

# from django.db import models

# Create your models here.

# dappx/models.py
from django.db import models
from django.contrib.auth.models import User
# from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# from django.contrib.auth import get_user_model

class UserProfileInfo(models.Model):
   fullname             = models.CharField(max_length=30)
  #  password             = models.CharField(blank=False, max_length=25)
   address              = models.TextField(blank=False, max_length=50)
   city                 = models.TextField(blank=False, max_length=20)
  #  email                = models.EmailField(max_length=60, verbose_name='email', unique=True)
   state                = models.TextField(default="Uttar Pradesh")
   mobile_no            = models.IntegerField()
   alt_mob_no           = models.IntegerField()
   profile_pic          = models.ImageField(upload_to='profile_pics',blank=True)
   user                 = models.OneToOneField(User,on_delete=models.CASCADE)
   date_joined          = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
   other_ref_names      = models.TextField(max_length=100)

   

   def __str__(self):
     return self.user.username
  
 

urls.py

dj9

VIEWS.PY



from django.shortcuts import render
from homepage.forms import UserProfileInfoForm, UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

def index(request):
    return render(request,'indexn.html')

@login_required
def special(request):
    return HttpResponse("You are logged in !")

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                print('found it')
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'registeration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account was inactive.")
        else:
            print("Someone tried to login and failed.")
            print("They used username: {} and password: {}".format(username,password))
            return HttpResponse("Invalid login details given")
    else:
        return render(request, 'login.html', {})

Inside templates folder

basen.html

Well, in below code I have used CSS along with HTML. This is not the developer’s way to do. They actually do so in separate folder named ‘static’ but due to my interest and convenience I have used the same HTML page. But its not an issue. All is good. Do as you are convenient.


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Base</title>
    <style>
      body{
        margin: 0px;
      }
      .emptyhead{
        height: 30px;
        background-color: #ff6f61;
      }
      .navbar{
        
        overflow: hidden;
        overflow: hidden;
        background-color:  black;
        position: fixed; /* Set the navbar to fixed position */
         /* Position the navbar at the top of the page */
        width: 100%; /* Full width */
      }
      
      /* Links inside the navbar */
      .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        margin-left: 6px;
        font-size: 22px;
      }
      
      /* Change background on mouse-over */
      .navbar a:hover {
        background: #ddd;
        color: red;
      }
      
      /* Main content */
      .main {
        margin-top: 80px; /* Add a top margin to avoid content overlay */;
      }
      .head{
        margin-top: 50px;
        background-color:  #ff6f61;
        color: white;
        height: 100px;
        font-size: 50px;
        font-family: monospace;
        font-weight: bold;
        text-align: center;
        padding: 35px;
      }
    </style>
</head>
  <body >
{# Django Home Link / Admin Link / Register Link#}
    <div class="emptyhead">

    </div>
    <div class="navbar">
          <a href="{% url 'index' %}">About Us</a>
          <a href="{% url 'admin:index' %}">Admin</a>
          <a href="{% url 'homepage:register' %}">Register</a>     
          {# Some logic on what to display for last item#}
          {% if user.is_authenticated %}
            <li><a href="{% url 'logout' %}">Logout</a></li>
          {% else %}
            <li><a href="{% url 'homepage:user_login' %}">Login</a></li>
          {% endif %}
    </div>
    <div class="head">
      PROVISION STORE MANAGEMENT SYSTEM
    </div>
    <div class="main">
    {% block body_block %}
    {% endblock %}
    </div>
  </body>
</html>

INDEXN.HTML

dj11

login.html

dj12

REGISTERATION.HTML

OVER!

Yes, over only thing you have to do is to download WAMP and through phpmyadmin create a database ‘provisionstore’. If you want to name something different then change the name in dj3 pic posted above too.

Happy Coding !

Please, Please, do ask your confusion. If any. Thanks 🙂

Functions in Python

Functions provide code re-usability i.e. once a function is written can be invoked anytime upon need.

They have one disadvantage too. They take more time to implement because the control has to jump from normal code to the functions and then returns back to the calling environment. This is known as Context Switching.

Information or data is passed to functions through parameters, if needed. Functions can be with or without parameters.

Functions if needed, can return some value or values or even a function. Thus function can have or cannot have return type.

List Comprehension in Python

List Comprehension is an excellent way to define a new List in just a single line.

Syntax: [function for var in iterable ]

—–> Let’s print all numbers within a given range

—–> Let’s print all numbers within a given range after adding 5 to them

—–> Let’s print all even numbers within a given range

Notice that function/expression is inserted at first place , for loop at second place and condition numbers%2==0 is inserted in the last.


List comprehension can be nested too.

Let me explain how.

Suppose we have a list of lists as-

myList = [ [11,22,33], [44,55,66], [77,88,99] ]

And I wish to print it in a flat format like this- 11, 22, 33, 44, 55, 66, 77, 88, 99.

Normally, we use following logic for implementation-

But things become Super Duper Easy when we implement using List Comprehension.

Okay so in above code, the control first is at for Lst in myList then it goes to for nums in Lst

and then it finally prints the nums . This follows exactly in the same sequence as in the code which is implemented without list comprehension.

—-> Now let’s print all Prime numbers using List Comprehension

—-> Print all Armstrong numbers within a given range

Without list comprehension-
Using List Comprehension

That’s it !

Happy Coding!

Practicing Lists(2)- Booking Management System


#             BOOKING MANAGEMENT SYSTEM
# 1. View all Seats
     # seats are from 1 to 50 only

# 2. Booking 
     # On Booking, the seat changes from 1 to B
     # If seat is already booked, then display a message

# 3. Cancellation
    # Change seat number from B to original number

# 4. Exit


print("\n\n\n-----------------------------------------------------------------------------")
print("-------------------------   Welcome to Python Booking System ------------------")

Seats = []
allBookedSeats =[]
check = True
for seat in range(1,51):
    Seats.append(seat)

while check:
    print()
    print("-------------------------------------------------------------------------------")
    print('''\n     Press
           1. View All Seats
           2. Book Your Seat
           3. Cancel your Booking
           4. Exit from System
        ''')
    print("-------------------------------------------------------------------------------")
    choice = int(input("Enter Your choice: "))


    # 1. ------------------------------------ View ALL Seats
    if choice==1:
        
        for seat in Seats:
            print(" ",seat, end=' ')
        print()
            

    # 2. -------------------------------------- Booking Seats
    if choice==2:
        show = 0
        
        # Show All Booked Seats to User
        print()
    
        for book_seat in allBookedSeats:
            print("Seat No.: ",book_seat+1," is Booked" )
            show += 1
        if show==0:
            print("All seats are Empty")
        
        # Booking Seats
        print()
        print("To book Your seat, Enter an Empty Seat Number: ")
        seat_num = int(input())
        if Seats.count(seat_num):
            Seats[seat_num-1] = 'BOOKED'
            allBookedSeats.append(seat_num-1)
            print("Your Seat is Successfully Booked! ")
        else:
            print("Oops! Seat is already Booked")

    # 3. ------------------------------------------ Cancel Booking
    if choice==3:
        cancel_seat = int(input("Enter Seat Number to cancel Your Booking: "))
        if type(Seats[cancel_seat-1])==int:
            print("This seat is already vacant ")
        else:
            Seats[cancel_seat-1] = cancel_seat
            print("Seat is Successfully Cancelled! ")
    
    # 4. ------------------------------------------ Exit    
    if choice==4:
        check = False
   




Practicing Lists in Python – Employee Management System


#                             EMPLOYEE MANAGEMENT SYSTEM

# 1. View all the details of employees
# 2. Inserting a new Employee
# 3. Deleting details of an Employee
# 4. Updating
# 5. Searching 
# 6. Exit
print("\n----------------------------------------------------------------")
print('''Press: 
                1 - View All Details of Employee
                2 - Insert New Employee
                3 - Delete an Employee
                4 - Update Employee's info
                5 - Search Details of an Employee
                6 - Exit
                ''') 
print("----------------------------------------------------------------")
emp_exit= True
Employee = []


while(emp_exit):
 print("\n----------------------------------------------------------------")
 choice = int(input("Enter Your Choice: "))

 #--------------------------------- View all details of Employee
 if choice==1:
  if len(Employee)==0:
   print("No Employees' details exists in the System")
  else:
   for employees in Employee:
    print(employees)

 #-------------------------------- Inserting New Employee
 if choice==2:
  print("You need to give Details Of Employee ")
  emp_id = int(input("\tID: "))
  
  # Checking Duplicate ID
  dup_id = 'NO'
  if len(Employee)!= 0:
   inc = 0
   for allemps in Employee:
    if Employee[inc][0]==emp_id:
     print("Oops! Employee with this ID already exists...")
     dup_id='YES'
     break
    else:
     inc += 1
  if dup_id=='NO':
   emp_name = input("\tName: ")
   emp_dept_no = int(input("Department No.: "))
   emp_salary = int(input("Salary: "))
   employees = []
   employees.append(emp_id)
   employees.append(emp_name)
   employees.append(emp_dept_no)
   employees.append(emp_salary)
   Employee.append(employees)

 #--------------------------------- Deleting Employee
 if choice==3:
  if len(Employee)==0:
   print("System contains 0 records...")
  else:
   inc = 0
   print("Do you want to Delete an Employee from the system?")
   ans = input("Yes/No ").upper()
   if ans=="YES":
    del_id = int(input("Enter ID of Employee which you want to Delete "))
    for allemps in Employee:
     if Employee[inc][0]==del_id:
      del(Employee[inc])
      inc += 1
     else:
      print("This Employee doesn't exist in the System")
      break
   else:
    pass

  # --------------------- Update Details of Emps
 if choice==4:
   if len(Employee)==0:
    print("System contains 0 records...")
   else:
    print("Please give ID of the Employee whose info you want to Update... ")
    updat_id = int(input("ID: "))
    print('''Press
              'N' for updating Name
              'S' for updating Salary
              'D' for updating Dept ID
              ''')
    ans = input().upper()
    inc = 0
    id_match_found = False
    for allemps in Employee:
     if Employee[inc][0]==updat_id:
      id_match_found = True
      if ans=='N':
       allemps[1] = input("Enter New Name of Employee ")
      if ans=='S':
       allemps[3]= int(input("Enter New Salary "))
      if ans=='D':
       allemps[2]= int(input("Enter New Dept. ID "))
     else:
      inc += 1
    
    # if ID is wrongly entered, then a message is sent to the user
    if not id_match_found:
     print("Oops! No Employee with this ID exists...")
 
 # ---------------------------- Searching an Employee 
 if choice== 5:
  if len(Employee)==0:
   print("System contains 0 records...")
  else:
   inc = 0
   print("Enter ID to search an Employee ")
   search_id = int(input())
   for allemps in Employee:
    if Employee[inc][0]==search_id:
     print(allemps)
  
 #------------------------------- Exit option
 if choice==6:
  emp_exit = False





Control Flow in Python

Python Program to show the use of if-statement :

parentheses after if statement is optional…

Python program to show the working of if-else statement:



Python program to show the working of if…elif…else statement:


Program to show the working of While loop:


Program to show the working of For-in loop:


Python Script to show the working of Pass Statement

Pass is used when we are not known how this condition should be handled but it is known that this condition is sure to occur. Remember, we cannot leave the body empty of any condition or any function.

Pass means nothing, it just passes the control to very next statement, if present.


Python Script to Show the Working of Break Statement:

Break allows to terminate from the loop/iteration immediately without executing the following statements in the loop, if the condition isn’t satisfied.


Python Script to show the working of Continue Statement:

Continue allows to skip only the current event if condition isn’t satisfied and proceed with the iteration.


range() Function in Python

range(start, stop, step)

Above syntax is of range() function. It has 3 parameters:

  • start: it is optional. It is the starting value and by default it is 0.
  • stop: it is required. It specifies the end value.
  • step: it is optional. And specifies the number of positions to be incremented.
Python Script to show the working of range() function:
Python program to print all Prime numbers:
Python program to print AP Series from 50 to 500 as first and last number respectively with difference of 17 :

Run the above codes and analyse the output. If any doubt feel free to post your problem in comments below.

Happy Coding!