checkbox from a bootstrap for loop from python/flask - python

HTML file (+Flask+Bootstrap)
{% extends "bootstrap/base.html" %}
{% block content %}
<html>
<head>
<style>
table, th, td {
background: #f5f5f5;
border-collapse: separate;
box-shadow: inset 0 1px 0 #fff;
font-size: 12px;
line-height: 24px;
margin: 30px auto;
text-align: left;
width: 800px;
}
.center {
text-align: center;
margin: auto;
width: 80%;
border: 3px solid rgba(0, 0, 0, 0);
padding: 20px;
}
.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
background-color: #efefef00;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<ul class="nav navbar-nav">
<a class="navbar-brand"> TMS </a>
<li>Routing</li>
</ul>
</div>
</nav>
<table style="width:auto" align="center">
<tr>
<th>
<p>Select the route sheet:</p>
<div class='center'>
<form ip="upload-form" action="{{ url_for('routing') }}" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" accept="/" multiple>
<input type="submit" action="submit" value="send">
</div>
</th>
</tr>
</table>
{% if ifHTMLConditional %}
<form method='POST' action="{{ url_for('routing') }}">
<table>
<tr>
<th>Name</th>
<th>Meters</th>
</tr>
{% for i in returnFromObjectClassRoute %}
<tr>
<td>
<input type="checkbox" name="vehicle" value= {{ i[1] }}>
{{ i[1] }}
</input>
</td>
<td>
{{ i[2] }}
</td>
</tr>
{% endfor %}
</table>
<input type="submit" value = {{ test.test }}>
{% endif %}
</form>
</body>
</html>
{% endblock %}
How could I use this for loop to create the number of checkboxes but with returns for using them in next functionalities.
The goal of the program is to create a Short Route. With the checkbox I want to let the user to select where is the startPoint for the algorithm
Python Code
#app.route('/routing', methods=['GET', 'POST'])
def routing():
test = Reference()
print(test.test.data)
if test == True:
return redirect('/home')
else:
if request.method == 'POST':
directory = os.path.join(APP_ROOT)
ifHTMLConditional = False
if not os.path.isdir(directory):
os.mkdir(directory)
for file in request.files.getlist("file"):
filename = file.filename
destination = "/".join([directory, filename])
if file.filename != '':
file.save(destination)
objectFromClassRoute = Route(filename, 'totalDistances_AB_BA_12012018.csv')
returnFromObjectClassRoute = objectFromClassRoute.routing1()
ifHTMLConditional = True
else:
returnFromObjectClassRoute = []
ifHTMLConditional = False
return redirect ('/home')
return render_template('routing.html', test=test, returnFromObjectClassRoute=returnFromObjectClassRoute, ifHTMLConditional=ifHTMLConditional)
return render_template('routing.html')
returnFromObjectClassRoute returns a list as a value.

Python code
An example for what I was looking for:
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = 'ThisIsSecret'
class Reference():
def testList(self):
testList = ['ABC', 'DEF', 'GHI']
return testList
#app.route('/home', methods=['GET', 'POST'])
def home():
test1 = Reference()
test = test1.testList()
print(test1.testList())
if request.method == "POST":
selected_contacts = request.form.getlist("test")
return render_template('checkBoxTest.html', test=test)
if __name__ == '__main__':
app.run(debug=True)
Html + Jinja2 code
<html>
<head>
</head>
<body>
<form method='POST' action="{{ url_for('home') }}">
{{ test.csrf_token }}
{% for i in test %}
<input type="checkbox" name="test" value="{{i}}">
<label>{{i}}</label>
{% endfor %}
<input type="submit" action="submit">
</form>
</body>
</html>
It returns all the check list you had activate before submitting and return a list of the values where you can used them as you want

Related

Save multiple items in same form django

let say these are the inputs of user, in my view it's well validated form.is_valid().
item code | description | unit | quantity
---------------------------------------------------------------
#itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1
#itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2
#itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3
reqeust.POST.getlist('description')
return a list -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3']
How can i save all the cells that the user enter to my MaterialIndent model??
just like in myview i could only save the last item only !!
# models
class MaterialIndent(models.Model):
material_indent_id = models.AutoField(primary_key=True)
date_request = models.DateTimeField(auto_now_add=True)
local_code = models.CharField(max_length=10, default='Local')
quotation = models.FileField(upload_to='files/', null=True, blank=True)
description = models.CharField(max_length=200)
unit = models.CharField(max_length=100)
quantity_requested = models.DecimalField(max_digits=12, decimal_places=2)
quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True)
request_for = models.CharField(max_length=50)
requester = models.ForeignKey(User, on_delete=models.CASCADE)
priority = models.CharField(max_length=100)
status = models.CharField(max_length=50, default='Store Checking')
def __str__(self):
return str(self.material_indent_id)
# form
class MaterialIndentForm(ModelForm):
class Meta:
model = MaterialIndent
fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation']
# views
def test(request):
available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True)
if request.method == 'POST':
form = MaterialIndentForm(request.POST, request.FILES)
if form.is_valid():
length = len(request.POST.getlist('local_code'))
post = form.save(commit=False)
for r in range(length):
local_code = request.POST.getlist('local_code')[r]
description = request.POST.getlist('description')[r]
unit = request.POST.getlist('unit')[r]
quantity_requested = request.POST.getlist('quantity_requested')[r]
post.local_code = local_code
post.description = description
post.unit = unit
post.quantity_requested = quantity_requested
post.requester = request.user
post.quantity_remained = post.quantity_requested
post.status = 'Store Checking'
post.save()
print('form is valid')
else:
print(form.errors)
else:
sparestock = SparePartsStock.objects.all()
form = MaterialIndentForm()
context = {'form': form, 'stock':available_stock, 'table': sparestock}
return render(request, 'copy.html', {})
# template
{% extends 'inventory.html' %}
{% load static %}
{% load crispy_forms_filters %}
{% block title %}
SG
{% endblock %}
{% block head %}
<style>
.container{
padding: 100px;
}
#priority_label{
margin-left: 15px;
}
#submit_button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
background-color: #555555;/* Black */
}
.btn {
background-color: DodgerBlue;
border: none;
color: white;
padding: 12px 16px;
font-size: 16px;
cursor: pointer;
}
/* Darker background on mouse-over */
.btn:hover {
background-color: RoyalBlue;
}
#rowAdder{
margin-left: 15px;
right: 10px;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
<script src="{% static 'js/jQuery.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
{% endblock %}
{% block content %}
<div class="container">
<h2 style="">Material Indent</h2>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="card">
<div class="card-header">
<label id="priority_label" for="rate">Priority</label><br>
<div class="rate">
<input type="radio" id="star5" name="priority" value="High" required/>
<label for="star5" title="High">High</label>
<input type="radio" id="star4" name="priority" value="Medium" required/>
<label for="star4" title="Medium">Medium</label>
<input type="radio" id="star3" name="priority" value="Low" required/>
<label for="star3" title="Low">Low</label>
</div>
<input name="request_for" type="text" class="form-control m-input" placeholder="Requested For" required><br>
<label for="quotation">Quotation: </label>
<input type="file" name="quotation" placeholder="Quotation">
</div>
<div class="card-body">
<div class="">
<div class="col-lg-12">
<div id="row">
<div class="input-group m-3">
<div class="input-group-prepend">
<button class="btn btn-danger"
id="DeleteRow" type="button">
<i class="bi bi-trash"></i>
-
</button>
</div>
<input id="local_code0" name="local_code0" type="text" class="form-control m-input" placeholder="Local Code" required list="localList">
<datalist id="localList">
{% for item in stock %}
<option value={{ item }}>
{% endfor %}
</datalist>
<input name="description0" type="text" class="form-control m-input" placeholder="Description">
<input name="unit0" type="text" class="form-control m-input" placeholder="Unit">
<input name="quantity0" type="text" class="form-control m-input" placeholder="Quantity">
</div>
</div>
<div id="newinput"></div>
<button id="rowAdder" type="button"
class="btn btn-dark">
<span class="bi bi-plus-square-dotted" id="plus_sign">
</span> +
</button>
<input type="hidden" name="length" id="length">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="button button5" id="submit_button">Submit</button>
</div>
</form>
</div>
<script type="text/javascript" >
let count = Number(1)
document.getElementById('length').value = 0
console.log(document.getElementById('length').value)
$("#rowAdder").click(function () {
document.getElementById('length').value = count
newRowAdd =
'<div id="row"> <div class="input-group m-3">' +
'<div class="input-group-prepend">' +
'<button class="btn btn-danger" id="DeleteRow" type="button">' +
'<i class="bi bi-trash"></i> - </button> </div>' +
'<input name=local_code' + count +' type="text" class="form-control m-input" placeholder="Local Code" list="localList" required>'+
'<input name=description'+count+ ' type="text" class="form-control m-input" placeholder="Description" required>'+
'<input name=unit'+count+ ' type="text" class="form-control m-input" placeholder="Unit" required>'+
'<input name=quantity'+count+ ' type="text" class="form-control m-input" placeholder="Quantity" required> </div> </div>'
;
$('#newinput').append(newRowAdd);
count ++
});
$("body").on("click", "#DeleteRow", function () {
$(this).parents("#row").remove();
count --
})
</script>
<script src="{% static 'js/material_indent_autofill.js' %}"></script>
{% include 'spare_parts_table.html' %}
{% endblock %}

Same results consecutif

I have a table : output _df (image in the question) .
Ienter image description here repetition of the same value for "PCR POS/Neg" consecutive in my "output_df".
If i have 3 results identiques consecutifs , more than 3 times in the output_df so i need to give an error message "WARNING" in my index.html
How i can do it ?
views.py
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
import pandas as pd
import datetime
from datetime import datetime as td
import os
from collections import defaultdict
from django.contrib import messages
import re
import numpy as np
def home(request):
#upload file and save it in media folder
if request.method == 'POST':
uploaded_file = request.FILES['document']
uploaded_file2 = request.FILES['document2']
if uploaded_file.name.endswith('.xls') and uploaded_file2.name.endswith('.txt'):
savefile = FileSystemStorage()
#save files
name = savefile.save(uploaded_file.name, uploaded_file)
name2 = savefile.save(uploaded_file2.name, uploaded_file2)
d = os.getcwd()
file_directory = d+'/media/'+name
file_directory2 = d+'/media/'+name2
cwd = os.getcwd()
print("Current working directory:", cwd)
results,output_df,new =results1(file_directory,file_directory2)
return render(request,"results.html",{"results":results,"output_df":output_df,"new":new})
else:
messages.warning(request, ' File was not uploaded. Please use the correct type of file')
return render(request, "index.html")
#read file
def readfile(uploaded_file):
data = pd.read_excel(uploaded_file, index_col=None)
return data
def results1(file1,file2):
results_list = defaultdict(list)
names_loc = file2
listing_file = pd.read_excel(file1, index_col=None)
headers = ['Vector Name', 'Date and Time', 'Test ID', 'PCR POS/Neg']
output_df = pd.DataFrame(columns=headers)
with open(names_loc, "r") as fp:
for line in fp.readlines():
line = line.rstrip("\\\n")
full_name = line.split(',')
sample_name = full_name[0].split('_mean')
try:
if len(re.split(r'(^[^\d]+)', sample_name[0])[2]) > 1:
sample_id = int(re.split(r'(^[^\d]+)', sample_name[0])[2])
else:
sample_id = int(re.split(r'(^[^\d]+)', sample_name[0])[2])
except:
sample_id = sample_name[0]
try:
if listing_file['Test ID'].isin([sample_id]).any():
line_data = listing_file.loc[listing_file['Test ID'].isin([sample_id])]
# The name of the file as it is shown in the folder
vector_name = line
# The data and the time of the taken sample
d_t = full_name[1].split('us_')[1].split('_')
date_time = td(int(d_t[0]), int(d_t[1]), int(d_t[2]), int(d_t[3]), int(d_t[4]), int(d_t[5]))
# Calculating the time frame from the swap to test of samples
date_index = list(line_data['Collecting Date from the subject'].iteritems())
for x in date_index:
if type(x[1]) is str():
date_time_obj = td.strptime(x[1], '%Y.%m.%d. %H:%M')
elif type(x[1]) is pd.Timestamp:
date_time_obj = x[1]
elif type(x[1]) is datetime.datetime:
date_time_obj = x[1]
frame_time = str(date_time - date_time_obj)
if date_time - date_time_obj > datetime.timedelta(hours=48):
results_list["List of samples with time frame over 48 :"].append(sample_id)
# The Test ID as it writen in the listing file
test_id = sample_id
# The PCR answer as it was written in the listing file
pcr_index = list(line_data['PCR Pos/Neg'].iteritems())
if len(pcr_index) > 1:
results_list["List of Samples with more than one attribute in the listing file:"].append(sample_id)
for x in pcr_index:
pcr_ans = x[1].strip()
values_to_add = {'Vector Name': vector_name,
'Date and Time': date_time,
'Test ID': test_id,
'PCR POS/Neg': pcr_ans,
'Time Frame': frame_time
}
row_to_add = pd.Series(values_to_add)
output_df = output_df.append(row_to_add, ignore_index=True)
else:
results_list["List of Samples not in the listing file:"].append(sample_name[0])
except:
print('The template name isnt good: {}'.format(sample_id))
output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time'])
new = output_df.groupby([output_df['Date and Time'].dt.date, 'PCR POS/Neg']).size().unstack(fill_value=0)
return dict(results_list), output_df.to_html(), new.to_html()
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet'>
</head>
<body id="ok" style=" width: 150; height: 100vh; background-size: cover;font-family: 'Poppins'; background-repeat:no-repeat; background-image: url('static/images/o.png'); ">
<br>
<br>
<nav class="navbar navbar-expand-lg navbar-white " style=" border-radius: 25px;box-shadow: inset 0 0 5px grey; margin:2em;background-color:#EDF1F6 ; 350px;">
<img src="static/images/mi2.png" style=" width: 350px; " >
<div class="container-fluid" style="text-align: center; margin: auto;">
<a class="navbar-brand" href="#"></a>
<button class="navbar-toggler" style="color:#0D4171;padding: 1px 1px;" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" >
<span class="navbar-toggler-icon"></span>⇩</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav" style="text-align: center; margin: auto;">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<li class="nav-item" style="#DAE2EA" >
<label class="btn btn-outline" style=" color: #0D4171;border-radius: 25px; font-size: 21px; text-align: center;">
<i class="fa fa-cloud-upload" style="font-size: 1.5em;"></i> <br>Listing files (.xls) <input type="file" name="document" id="document" required="required">
</label>
<label class="btn btn-outline" style=" color: #0D4171; font-size: 21px;">
<i class="fa fa-cloud-upload" style="font-size: 1.5em;"></i> <br>File Names (.txt) <input type="file" name="document2" id="document2" required="required">
</label>
<br>
<div style="margin: auto;">
<br>
<button class="btn" style="background-color: #0D4171; border: none; ;color: white; padding: 10px 25px; text-decoration: none;
font-size: 16px;font:Poppins Medium; border-radius: 15px; margin-right:65px;" > Upload </button>
</div>
</li>
</form>
</ul>
{% block messages %}
{% if messages %}
{% for message in messages %}
{% endfor %}
{% endif %}
{% endblock %}
</div>
</div>
</nav>
{%block body%}{% endblock body%}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
<div class="">
<h1></h1>
<p></p>
<p></p>
</div>
{{variable}}
</body>
</html>
results.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet'>
<meta charset="UTF-8">
<title> Dashboard Result</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnPrint").live("click", function () {
var divContents = $("#dvContainer").html();
var printWindow = window.open('', '', 'height=100,width=200');
printWindow.document.write('<html><head><title> ListingCheckPdf</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
});
</script>
</head>
<body id="ok" style="margin:0.5; padding:0.5em; width: auto;background-size: cover;font-family: 'Poppins'; height:auto; background-size: cover; background-repeat:no-repeat; background-image: url('static/images/o.png'); ">
<nav class="navbar navbar-expand-lg navbar-white " style=" border-radius: 25px; margin:2em;background-color:#EDF1F6 ; ">
<img src="static/images/mi3.png" style=" width: 250px; margin-left:1em;" >
<form id="form1">
<br>
<input type="button" style="background-color: #0D4171; border: none; color: white; padding: 8px 18px; text-align: center; text-decoration: none; display: inline-block; font-size: 15px; margin-left:30px; font-family: 'Poppins'; border-radius: 25px;" value="Download PDF" id="btnPrint" /><br><br><br>
<div class="container-fluid" id="dvContainer" style="width: 900px;height: 900px; border-radius:15px; background-color:white; margin:auto; box-shadow: inset 0 0 5px grey;border-radius: 10px; overflow: scroll; /* showing scrollbars */" >
<style>table, td, th { margin-left: auto; margin-right: auto; border: 1px solid black; width: 600px; text-align:center; align-items: center;} </style> <br>
<div>
{% autoescape off %}{{ new }}{% endautoescape %}
</div><br><br>
<div style="color: hidden; margin: 30px; font: Poppins; font-size: 17px">
{% for key, value in results.items %}<br>
{{ key }}<br>
{% for elem in value %}
<div style="margin-left:50px" >
- {{elem }} <br></div>
{% endfor %}
{% endfor %}</div><br><br><br><br><br>S
<div>{% autoescape off %}{{ output_df }}{% endautoescape %}</div>
</div>
</form>
</body>
</html>

Creating Relational database with user model in Django. I think i have created relational database but i don't know whats going wrong

I think i have successfully created relation between user model and another table called shop_details but the data is not been inserted. i don't know what is going wrong.
the code is here.
models.py
from django.db import models
from django.contrib.auth.models import User
class Shop_Details(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
shop_name = models.CharField(max_length=50)
shop_street = models.TextField()
shop_area = models.TextField()
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pin_code = models.TextField()
my views.py is here
views.py
def shop_detils(request):
if request.method == "POST":
shop_name = request.POST['shop_name']
shop_street = request.POST['shop_street']
shop_area = request.POST['shop_area']
city = request.POST['city']
state = request.POST['state']
pin_code = request.POST['pin_code']
if(len(str(pin_code))!=6):
messages.info(request,"please provide a valid address pin-code")
print("niceee...........................")
return render(request,'shop_details.html')
else:
if(is_number(int(pin_code))):
shop = Shop_Details(shop_name=shop_name,shop_street=shop_street,shop_area=shop_area,city=city,state=state,pin_code=pin_code,user=request.user)
shop.save()
messages.info(request,"Shop Details Updated")
shop_data = Shop_Details.objects.filter(user = request.user)
print(shop_data[1])
print("congrats...........................")
return redirect('home',{'data':shop_data})
else:
messages.info(request,"please provide a valid address")
print("nice2222222222222222222222222")
return render(request,'shop_details.html')
else:
return render(request,'shop_details.html')
my shop_details.html is here
shop_detsils.html
enter code here
{% extends 'layout.html' %}
{% csrf_token %}
{% if user.is_authenticated %}
{% csrf_token %}
{% load static %}
{% csrf_token %}
<meta name="viewport" content="width=device-width, initial-scale=1">
{% csrf_token %}
<body align="center">
{% csrf_token %}
{% csrf_token %}
{% csrf_token %}
{% block content %}
<form action="shop_detils" method="POST">
{% csrf_token %}
<div align="center" class='resp_code frms'>
{% csrf_token %}
<p align='center'<h5><font style='font: 1em/1.3em Tahoma,Geneva,sans-serif;'>
<b>Shop Details</b></font></h5></p>
<div id="selection">
{% csrf_token %}
<table>
{% csrf_token %}
<tr><td>Shop Name: </td><td><input required style="width:200%;" name="shop_name" type="text"></td></tr>
<tr><td>Shop Street: </td><td><input required style="width:200%;" name="shop_street" type="text"></td></tr>
<tr><td>Shop Area: </td><td><input required style="width:200%;" name="shop_area" type="text"></td></tr>
<tr><td>City: </td><td><input required style="width:200%;" name="city" type="text"></td></tr>
<tr><td>State: </td><td><input required style="width:200%" list="state" name="state" type="text"></td></tr>
<datalist id="state">
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
<option value="Arunachal Pradesh">Arunachal Pradesh</option>
<option value="Assam">Assam</option>
<option value="Bihar">Bihar</option>
<option value="Chandigarh">Chandigarh</option>
<option value="Chhattisgarh">Chhattisgarh</option>
<option value="Dadar and Nagar Haveli">Dadar and Nagar Haveli</option>
<option value="Daman and Diu">Daman and Diu</option>
<option value="Delhi">Delhi</option>
<option value="Lakshadweep">Lakshadweep</option>
<option value="Puducherry">Puducherry</option>
<option value="Goa">Goa</option>
<option value="Gujarat">Gujarat</option>
<option value="Haryana">Haryana</option>
<option value="Himachal Pradesh">Himachal Pradesh</option>
<option value="Jammu and Kashmir">Jammu and Kashmir</option>
<option value="Jharkhand">Jharkhand</option>
<option value="Karnataka">Karnataka</option>
<option value="Kerala">Kerala</option>
<option value="Madhya Pradesh">Madhya Pradesh</option>
<option value="Maharashtra">Maharashtra</option>
<option value="Manipur">Manipur</option>
<option value="Meghalaya">Meghalaya</option>
<option value="Mizoram">Mizoram</option>
<option value="Nagaland">Nagaland</option>
<option value="Odisha">Odisha</option>
<option value="Punjab">Punjab</option>
<option value="Rajasthan">Rajasthan</option>
<option value="Sikkim">Sikkim</option>
<option value="Tamil Nadu">Tamil Nadu</option>
<option value="Telangana">Telangana</option>
<option value="Tripura">Tripura</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
<option value="Uttarakhand">Uttarakhand</option>
<option value="West Bengal">West Bengal</option>
</datalist>
<tr><td>Pin-code: </td><td><input required name="pin_code" type="text"></td></tr>
</table>
<input style="border-radius: 0.5em; background-color:rgba(2, 2, 253, 0.753);
width:2.5cm;height:0.8cm; font-family: sans-serif;" type="submit" value="Submit">
</div>
</div>
</form>
{% endblock %}
</body>
{% endif %}
my layout.html is here. basically Iam extending layout.html in all html files.
layout.html
<!DOCTYPE html>
{% load static %}
{% csrf_token %}
<html>
<title>GrocSale</title>
<head>
<script language="Javascript" href="{% static 'js/jquery.js' %}"></script>
<script type="text/JavaScript" href="{% static 'js/state.js'%}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'style.css'%}">
</head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
{% csrf_token %}
<style>
* {box-sizing: border-box}
body{
background:url("{% static 'groc.jpeg' %}") no-repeat;
background-size:cover ;
background-attachment:fixed;
}
body:after {
content: "";
position: fixed;
top: 0; bottom: 0; left: 0; right: 0;
background: hsla(180,0%,50%,0.25);
pointer-events: none;
}
.tab {
float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 20%;
height: 1000px;
}
/* Style the buttons that are used to open the tab content */
.tab button {
display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current "tab button" class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
}
.divs{
width: 300px;
height: 300px;
border: 1px solid green;
padding: 50px;
float: left;
border-radius: 1em;
box-shadow: 10px 10px;
margin-right: 15px;
margin-left: 15px;
margin-top: 15px;
}
.divs:hover:not(.active) {
background-color: gold;
cursor: grab;
}
</style>
<body>
{% csrf_token %}
<header align="center" style="height: 150px;background-color:orange">
{% csrf_token %}
<strong>
{% csrf_token %}
{% for detail in data%}
<h1>{{detail.shop_name}}</h1>
<h4>Arokya,Hatsun,Arun All Products Available Here</h4>
<h6>{{detail.shop_street}}{{detail.shop_area}}, {{detail.city}}, {{detail.state}} - {{detail.pin_code}}</h6>
{% endfor %}
</strong>
</header>
<div style="background-color:orange;" class="tab" >
{% csrf_token %}
<button class="w3-bar-item w3-button" >Home</button>
<button class="w3-bar-item w3-button" >Add/Update Product</button>
<button class="w3-bar-item w3-button" >Add Stock/Update Stock</button>
<button class="w3-bar-item w3-button" >Add Sale</button>
<button class="w3-bar-item w3-button" >Total Sale</button>
<button class="w3-bar-item w3-button" >Daily Collection Customers</button>
<button class="w3-bar-item w3-button" >Today's Collection Status</button>
<button class="w3-bar-item w3-button" >Show Products</button>
<button class="w3-bar-item w3-button" >All Stock Orders</button>
<button class="w3-bar-item w3-button" >Settings</button>
<a href="{% url 'shop_detils' %}" ><button class="w3-bar-item w3-button" >Shop Details</button></a>
<button class="w3-bar-item w3-button" >Contact Us</button>
<button class="w3-bar-item w3-button" >Logout</button>
</div>
{% block content %}
{% endblock %}
</body>
</html>
Iam still a learner in Django.
Thanks in advance.
my error is shown in image
enter image description here

Django/WeasyPrint: Bangla Font Rendering Issue

My Python Version 3.6+, Django version 1.11.6 and OS: Windows-10 64bit.
I am creating the PDF file with weasyprint within Django project. But the problem is Bengali font is not rendering. Please check this screenshot.
Now this is my views.py file
def get_pdf_file(request, customer_id, sys_type):
sys_type = customer_id
area = "pdf"
site_credit = site_credit1
time_now = timezone.now()
customers = get_object_or_404(CustomerInfo, pk=customer_id)
due_taka_track = customers.duetaka_set.all()
if due_taka_track == None:
due_taka_track = 0
unpaid_taka = int(customers.customer_price -
customers.customer_due_taka_info)
due_taka_track = customers.duetaka_set.all()
sum_cost_taka = due_taka_track.aggregate(
sp=Sum('customer_due')).get('sp', 0)
if sum_cost_taka == None:
sum_cost_taka = 0
total_paid_taka = sum_cost_taka + customers.customer_due_taka_info
payment_status = 'complete'
payment_message = ' '
remain_taka='Full Paid '
remain_msg=''
if customers.customer_due_taka_info < customers.customer_price:
payment_status = 'incomplete'
payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি'
remain_msg='টাকা বাকী আছে'
baki_ase="পাওনা আছে "
remain_taka = customers.customer_price - customers.customer_due_taka_info
context = {'customers': customers,
'sys_type': sys_type,
'area': area,
'site_credit': site_credit,
'site_name': 'Moon Telecom',
'sys_type': sys_type,
'due_taka_track': due_taka_track,
'total_paid_taka': total_paid_taka,
'payment_message': payment_message,
'time_now': time_now,
'unpaid_taka': unpaid_taka,
'payment_message': payment_message,
'remain_taka': remain_taka,
'sum_cost_taka': sum_cost_taka,
'remain_msg': remain_msg}
html_string = render_to_string('shop/pdf_invoice.html', context).encode(encoding="UTF-8")
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename=invoice' + \
str(customers.id)+customers.customer_uid + customers.customer_name + '.pdf'
HTML(string=html_string).write_pdf(response)
return response
and this is my html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-16">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>invoice copy {% if customers.customer_name %}Customer Name:{{customers.customer_name}}{% else %}
Name: দেওয়া হয়নি{% endif %} | {{customers.customer_uid}}</title>
<head>
<style>
#import url('https://fonts.maateen.me/siyam-rupali/font.css');
table,
th,
td {
border: 1px solid black;
}
th,
td {
padding: 5px;
text-align: left;
}
p,th,td,th,tr{
font-size:10px;line-height:12px
font-family: 'SiyamRupali', sans-serif;
}
.border_sx {
border-style: solid;
border-width: 1px;
padding: 5px;
border-radius: 5px;
display:block;
width: 100%;
margin-right:-100px;
padding: 10px;
}
#background{
position:absolute;
z-index:0;
background:white;
display:block;
min-height:50%;
min-width:50%;
color:yellow;
}
#content{
position:absolute;
z-index:0.1;
}
#bg-text
{
color:lightgrey;
font-size:70px;
margin-top: 160px;
margin-right: 40px;
transform:rotate(320deg);
-webkit-transform:rotate(300deg);
}
#bg-text-one
{
color:lightgrey;
font-size:20px;
line-height: 25px;
margin-right: 100px;
margin-bottom: 800px;
margin-top: -10px;
transform:rotate(320deg);
-webkit-transform:rotate(300deg);
}
#fix_font
{
font-size: 13.5px;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
}
</style>
</head>
<body>
<div id="background">
<p id="bg-text">Moon Telecom</p>
<p id="bg-text-one">Fulhata Bazar জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ। 01717-051200(সুকান্ত বসু) 01828-163858(দোকান)</p>
</div>
<div id="content" class="border_sx">
<div class="invoice_intro">
<div class="site_title" style="text-align:center; margin:0 auto">
<h1 style="font-size:10px;line-height:12px">ওঁ</h1>
<p style="font-size:8px;line-height:10px">মা কালী সহায়</p>
<h2 style="font-size:19px;line-height:13px;">মুন টেলিকম</h2>
<div class="invoice_info_one" style="width:70%;margin:0 auto; text-align:center">
<p style=";">সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার,
ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p>
</div>
<div class="invoice_location">
<p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p>
</div>
<div class="invoice_contact">
<p>01717-051200(সুকান্ত বসু) 01828-163858(দোকান)
<b>Email:</b> moontelecom2008#gmail.com</p>
</div>
<hr>
</div>
</div>
<div class="customer_part" style="width:40%;margin:0px left;display:block">
<div class="customer_info">
{% if customers.customer_name %}
<p style="font-size:">Customer Name:
<b> {{customers.customer_name}}</b>
</p>
{% else %}
<p> Name: দেওয়া হয়নি</p> {% endif %}
<p style="font-size:x">Phone Number: {% if customers.customer_mobile_no %} {{customers.customer_mobile_no}} {% else %} No Mobile Number
{% endif%}
</p>
<p style="font-size:">Purchase Time: {{customers.customer_sell_date}}</p>
<p style="font-size:">invoice id:
<b>{{customers.customer_uid}}</b>
</p>
<p>{{customers.product_warrenty}}</p>
</div>
</div>
<div class="">
<table style="border-style: solid;border-width: 0px;">
<tr>
<th>Product Name</th>
<th colspan="">Price</th>
<th>Product Price (MRP)</th>
<th>ID or IME</th>
<th>Warrenty</th>
<th>QN</th>
</tr>
<tr>
<td>
<b>{{customers.customer_product_name}}</b>
</td>
<td>
<b>Customer Price: {{customers.customer_price}}</b> TK
<i>{% if customers.customer_discount_taka %}
( Discount added {{customers.customer_discount_taka}} TK )
{% else%}
{%endif%}</i>
</td>
<td>{{customers.customer_product_mrp}} Taka * {{customers.customer_product_quantity}} (QN) </td>
<td>{{customers.customer_product_id}}</td>
<td>
{% if customers.customer_product_warrenty %} {{customers.customer_product_warrenty}} Months {% else %} No {% endif %}
</td>
<td>{{customers.customer_product_quantity}}</td>
</tr>
<th>
First Time Payment
</th>
<th>
{{customers.customer_first_time_payment}} TK
<span style="color:red">{{customers.customer_first_due_info}}</span>
</th>
<td>
{{customers.customer_sell_date}}
</td>
{% if due_taka_track %}
<tr>
<th>SL</th>
<th>Taka</th>
<th>Paid Date</th>
<th>Due Info</th>
</tr>
<hr> {% for track in due_taka_track %}
<tr>
<td>{{forloop.counter}}</td>
<td>
<i>{{track.customer_due}}</i> TK</td>
<td>{{track.customer_due_date}}</td>
<td>{{track.customer_due_info}}</td>
</tr>
{% endfor %} {% else %} {% endif %} {% if sum_cost_taka %}
<tr>
<td>Total Due Complete </td>
<th>{{sum_cost_taka}} TK</th>
</tr>
{% else %} {% endif %}
<tr>
<td>
<b>Total Paid</b>
</td>
<th>
{% if payment_message %}
{{customers.customer_due_taka_info}} TK
<span style="color:red">{{payment_message}}</span>
<br>
<button type="button" class="btn btn-danger">{{remain_msg}} {{remain_taka}}TK</button>
{%else %} {{customers.customer_due_taka_info}} TK
<button type="button" class="btn btn-success">Payment Completed</button>
{% endif %}
</th>
</tr>
</table>
<table border="none!important" style="margin-top:10px;border:none!important">
<tr>
<th style="text-align:left">Customer signature</th>
<th style="text-align:right">Authorized signature</th>
</tr>
</table>
</div>
<div class="customer_notifications">
<div class="container">
<div class="row">
<div class="col-lg-12">
{% if customers.customer_conditions %}
<div class="warning">
<p>
<i>{{customers.customer_product_name}} {{customers.customer_conditions}}</i>
</p>
</div>
{% else %} {% endif %}
<div class="col-lg-12">
<div class="footer_info">
<p id="fix_font"><b>বিঃদ্রঃ ডেলিভারির সময় মাল বুঝিয়া নিবেন। পরে কোন আপত্তী গ্রহনযোগ্য নয়। (বিক্রিত মাল ফেরত হয় না) </h6>
<p>Print date: {{time_now}}</b></p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer" style="display:block">
<div class="footer_info">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="footer_info">
<div class="copy_right">
{% if site_credit %}
<p>{{site_credit}}</p>
{% else %} {% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I changed UTF-8/UTF but this issue did not fix.
I installed(Kalpurush) font on my PC. Then I added that font write_pdf variable.
HTML(string=html_string).write_pdf(response,stylesheets=[CSS(string='body,p,h1,h2,h3,h4,h5,tr,td { font-family: Kalpurush !important }')])

how to stack Vertically or Horizontally two MultiCheckboxField wtform fields

i have a form that uses a widget. what i want is two vertical columns side by side with the checkboxes.
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class SimpleForm2(Form):
menu_items = MultiCheckboxField('Menu Item', choices=[], coerce=int)
contents = MultiCheckboxField('Content', choices=[], coerce=int)
submit = SubmitField('OK')
for example
Menu Item | Content
cbox1 | cbox1'
This is a Horizontal stacking
This answer did all the work
css stacking
from flask_wtf import Form
class SimpleForm2(Form):
menu_items = MultiCheckboxField('Menu Item', choices=[], coerce=int)
# contents = MultiCheckboxField('Content', choices=[], coerce=int)
# submit = SubmitField('OK')
class SimpleForm3(Form):
# menu_items = MultiCheckboxField('Menu Item', choices=[], coerce=int)
contents = MultiCheckboxField('Content', choices=[], coerce=int)
# submit = SubmitField('OK')
#manage.route('/test', methods=['GET', 'POST', 'PUT', 'DELETE'])
#login_required
def test(menu_item_id=None):
form = SimpleForm2()
form1 = SimpleForm3()
form1.contents.choices = [(x.id, x.name) for x in MenuItemContent.query.filter_by(store_id=current_user.id).all()]
form.menu_items.choices = [(x.id, x.product_name) for x in MenuItem.query.filter_by(store_id=current_user.id).all()]
info = []
if form.validate_on_submit() and form1.validate_on_submit():
menu_item = form.data['menu_items']
contents = form1.data['contents']
for mid in menu_item:
info = []
for c in contents:
info.append({"menu_content_id": c,
"default": 0,
"cost": 0})
MenuManager(db.session).create_menu_with_content_relationship(store_id=current_user.id,
menu_id=mid,
menu_content_info=info)
return render_template('manage/form_test.html', form=form, form1=form1)
form_test.html
{% include "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% from "macros.html" import render_field %}
{% block page_content %}
{% macro render_form44(form, action_url='', action_text='Submit', class_='', btn_class='btn btn-default') -%}
<!-- <form method="POST" action="{{ action_url }}" role="form" class="{{ class_ }}"> -->
{{ form.hidden_tag() if form.hidden_tag }}
{% if caller %}
{{ caller() }}
{% else %}
{% for f in form %}
{% if f.type == 'BooleanField' %}
{{ render_checkbox_field(f) }}
{% elif f.type == 'RadioField' %}
{{ render_radio_field(f) }}
{% else %}
{{ render_field(f) }}
{% endif %}
{% endfor %}
{% endif %}
<!-- <button type="submit">OK</button>
</form> -->
{%- endmacro %}
<style type="text/css">
fieldset.group {
margin: 0;
padding: 0;
margin-bottom: 1.25em;
padding: .125em;
}
fieldset.group legend {
margin: 0;
padding: 0;
font-weight: bold;
margin-left: 20px;
font-size: 100%;
color: black;
}
ul.checkbox {
margin: 0;
padding: 0;
margin-left: 20px;
list-style: none;
}
ul.checkbox li input {
margin-right: .25em;
}
ul.checkbox li {
border: 1px transparent solid;
display:inline-block;
width:12em;
}
ul.checkbox li label {
margin-left: ;
}
ul.checkbox li:hover,
ul.checkbox li.focus {
background-color: lightyellow;
border: 1px gray solid;
width: 12em;
}
.checkbox {
-webkit-column-count: 6; /* Chrome, Safari, Opera */
-moz-column-count: 6; /* Firefox */
column-count: 6;
}
</style>
<form method="POST" role="form">
<fieldset class="group">
<legend>Pick Menu Items</legend>
<ul class="checkbox">
{{ render_form44(form) }}
</ul>
</fieldset>
<fieldset class="group">
<legend>Pick Contents</legend>
<ul class="checkbox">
{{ render_form44(form1) }}
</ul>
</fieldset>
<button type="submit">OK</button>
</form>
{% endblock %}

Categories

Resources