Popular Posts

Showing posts with label Project. Show all posts
Showing posts with label Project. Show all posts

Nov 24, 2020

Working with Django! Developing ecommerce site…



Github : https://github.com/itsjubayer/GreenShop-Django.git


Create a new project called ‘PyBuy’ and install Django from terminal:

Command: pip install django==2.1

 


-now create django project: go to terminal and press ctrl+l to clear the terminal then type this command to create project

> django-admin startproject pybuy .  [here .(period) means current directory, there must be a space before period]

 





-          Execute this command to run the development web server

Python manage.py runserver



 Database migration:

Go to PyShop/settings.py and in line 33 installed_apps add this line:

INSTALLED_APPS = [
   
'django.contrib.admin',
   
'django.contrib.auth',
   
'django.contrib.contenttypes',
   
'django.contrib.sessions',
   
'django.contrib.messages',
   
'django.contrib.staticfiles',
   
'products.apps.ProductsConfig'
]

 

Execute the command in the terminal:

>python manage.py makemigrations

Then execute this command:

>python manage.py migrate

 

Create super admin user:

>python manage.py createsuperuser

 

Browse url : http://127.0.0.1:8000/admin

Add product module to admin panel:

Go to Products/admin.py and add this lines

from django.contrib import admin
from .models import Product


admin.site.register(Product)

 

refresh add panel page.



Customize product columns:

Go to products/admin.py and update code

from django.contrib import admin
from .models import Product

#to customize column
class ProductAdmin(admin.ModelAdmin):
    list_display = (
'name', 'price', 'stock')

#add ProductAdmin to register to customize columns for products admin panel
admin.site.register(Product, ProductAdmin)


Add offer:

Update the code of admin.py

from django.contrib import admin
from .models import Product, Offer


class OfferAdmin(admin.ModelAdmin):
    list_display = (
'code', 'discount')


#to customize column
class ProductAdmin(admin.ModelAdmin):
    list_display = (
'name', 'price', 'stock')


admin.site.register(Offer
, OfferAdmin)
#add ProductAdmin to register to customize columns for products admin panel
admin.site.register(Product, ProductAdmin)

 



-Designing the landing page for visitors:

  -Create a  directory to products folder and named it templates(careful at typing the name templates because django looks for this directory during loading)

- create an html page and named it ‘index.html’

<h1>Products</h1>
<ul>
    <li>
Item1</li>
    <li>
Item1</li>
    <li>
Item1</li>
</ul>

 

Update the code of views.py page:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Product


def index(request):
   
products = Product.objects.all()
   
return render(request, 'index.html')


def new(request):
   
return HttpResponse('new products')

 

to make the page dynamic update views.py page by changing this line:

return render(request, 'index.html', {'products': products})

here we are returning a dictionary

 

update index.html

<h1>Products</h1>
<ul>
  
{% for product in products %}
   
<li>{{ product.name }} (${{ product.price }})</li>
   
{% endfor %}
</ul>

 

Reload the url:

http://127.0.0.1:8000/products/



 Add Bootstrap:

Create a new html file in template and named it base.html.

Go to getbootstrap.com and from documentation copy the line of code and paste it to base.html file:

<!doctype html>
<html
lang="en">
  <head>
   
<!-- Required meta tags -->
   
<meta charset="utf-8">
    <meta
name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

   
<!-- Bootstrap CSS -->
   
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>
Hello, world!</title>
  </head>
  <body>
   

  <!-- As a link  -->
<nav class="navbar navbar-light bg-light">
  <a
class="navbar-brand" href="#">PyShop</a>
</nav>

  <div
class="container">
       
{% block content %}
        {% endblock %}
 
</div>


   
<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
   
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>

    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>

 

 Update index.html

{% extends 'base.html' %}

{% block content %}
   
<h1>Products</h1>
    <ul>
      
{% for product in products %}
       
<li>{{ product.name }} (${{ product.price }})</li>
       
{% endfor %}
   
</ul>
{% endblock %}

 

 Rendering Cards:

 Go to https://getbootstrap.com/docs/4.5/components/card/ and copy the required code.

 And Navbar

{% extends 'base.html' %}

{% block content %}
<h1>Products</h1>
<!--
 div.row + press tab
 div.col + press tab
 -->
<div class="row">
   
{% for product in products %}

       
<div class="col">
    <div
class="card" style="width: 18rem;">
        <img
src="{{ product.image_url}}" class="card-img-top" alt="...">
        <div
class="card-body">
            <h5
class="card-title">{{ product.name }}</h5>
            <p
class="card-text">${{ product.price }}</p>
            <a
href="#" class="btn btn-primary">Add to Cart</a>
        </div>
    </div>
    </div>

   
{% endfor %}

</div>

{% endblock %}

 

To reuse the templates base.html we have to create templates directory to main folder PyShop and move the file base.html in it.

Update PyShop>settings.py file

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

 Working with excel:

import openpyxl as xl
from openpyxl.chart import BarChart, Reference


wb = xl.load_workbook(
'transaction.xlsx')
sheet = wb[
'Sheet1']
#cell = sheet['a1']
#cell = sheet.cell(1, 1) #row, column
#print(sheet.max_row)

for row in range(2, sheet.max_row+1):
        cell = sheet.cell(row
, 3)
        corrected_price = cell.value
        corrected_price_cell = sheet.cell(row
, 4)
        corrected_price_cell.value = corrected_price

values = Reference(sheet
,
                  
min_row=2,
                  
max_row=sheet.max_row,
                  
min_col=4,
                  
max_col=4)

chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart
, 'e2')

wb.save(
'correct_transaction.xlsx')

 After Refactoring:

import openpyxl as xl
from openpyxl.chart import BarChart, Reference



def process_workbook(filename):
        wb = xl.load_workbook(filename)
        sheet = wb[
'Sheet1']
       
for row in range(2, sheet.max_row+1):
                cell = sheet.cell(row
, 3)
                corrected_price = cell.value
                corrected_price_cell = sheet.cell(row
, 4)
                corrected_price_cell.value = corrected_price

        values = Reference(sheet
,
                          
min_row=2,
                          
max_row=sheet.max_row,
                          
min_col=4,
                          
max_col=4)

        chart = BarChart()
        chart.add_data(values)
        sheet.add_chart(chart
, 'e2')

        wb.save(filename)

process_workbook(
'transaction.xlsx')

 output:


Jul 8, 2020

Python OpenCV Project: Attendance

Create File and named it Attendance.csv
Create directory ImagesBasic and ImagesAttendance
Put original images to ImagesAttendance and in ImagesBasic put test images
Install Required packages. Stable version of Dlib package version is 19.18
To add packages go the settings->


Install c++








import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime

path =
'ImagesAttendance'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
for c1 in myList:
    curImg = cv2.imread(
f'{path}/{c1}')
    images.append(curImg)
    classNames.append(os.path.splitext(c1)[
0])
print(classNames)

def findEncodings(images):
    encodeList = []
   
for img in images:
        img = cv2.cvtColor(img
, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[
0]
        encodeList.append(encode)
   
return encodeList

def markAttendance(name):
   
with open('Attendance.csv','r+') as f:
        myDataList = f.readlines()
        nameList = []
       
for line in myDataList:
            entry = line.split(
',')
            nameList.append(entry[
0])
       
if name not in nameList:
            now = datetime.now()
            dtString = now.strftime(
'%H:%M:%S')
            f.writelines(
f'\n{name}, {dtString}')
           
# print(myDataList)

encodeListKnown = findEncodings(images)
#print(len(encodeListKnown))
print('Encoding Complete')

cap = cv2.VideoCapture(
0)
while True:
    success
, img = cap.read()
    imgS = cv2.resize(img
, (0,0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS
, cv2.COLOR_BGR2RGB)

    facesCurFrame = face_recognition.face_locations(imgS)
    encodesCurName = face_recognition.face_encodings(imgS
, facesCurFrame)

   
for encodeFace, faceLoc in zip(encodesCurName, facesCurFrame):
        matches = face_recognition.compare_faces(encodeListKnown
, encodeFace)
        faceDis = face_recognition.face_distance(encodeListKnown
, encodeFace)
       
#print(faceDis)
       
matchIndex = np.argmin(faceDis)

       
if matches[matchIndex]:
            name = classNames[matchIndex].upper()
           
print(name)
            y1
, x2, y2, x1 = faceLoc
            y1
, x2, y2, x1 =  y1*4, x2*4, y2*4, x1*4
           
cv2.rectangle(img, (x1, y1), (x2, y2),(0,255,0),2)
            cv2.rectangle(img
, (x1, y2-35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img
, name,(x1+6, y2-6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)


    cv2.imshow(
'WebCam', img)
    cv2.waitKey(
1)