why Show data in Angle brackets 'example',) in Django Form - django

HTML CODE
{% csrf_token %}
<input type="text" name="sub1" value="{{sub1}}" placeholder="Sub 1">
<input type="text" name="sub2" value="{{sub2}}" placeholder="Sub 2">
<input type="text" name="sub3" value="{{sub3}}" placeholder="Sub 3">
<input type="text" name="sub4" value="{{sub4}}" placeholder="Sub 4">
<input type="text" name="sub5" value="{{sub5}}" placeholder="Sub 5">
<button type="submit">SUBMIT</button>
</form>
VIEWS FUNCTION
def Contact(request):
data= {}
try:
if request.method=="POST":
sub1= request.POST.get('sub1'),
sub2= int(request.POST.get('sub2')),
sub3= int(request.POST.get('sub3')),
sub4= int(request.POST.get('sub4')),
sub5= int(request.POST.get('sub5')),
Total_num = sub1+sub2+sub3+sub4+sub5
print(sub1)
data = {
'Total_num':Total_num,
'sub1':sub1
}
except:
pass
return render(request,"contact.html",data)
OUTPUT
{{sub1}}
Result
('ad',)

You should remove the trailing commas: by the comma at the end, you wrap the value in a singleton tuple. By removing the comma, you get the real value, so:
sub1 = request.POST.get('sub1')
sub2 = int(request.POST.get('sub2'))
sub3 = int(request.POST.get('sub3'))
sub4 = int(request.POST.get('sub4'))
sub5 = int(request.POST.get('sub5'))
Total_num = sub1+sub2+sub3+sub4+sub5

Related

How to insert selected items to db in django?

Here is my Template :
{% for pr in productlist %}
<ul>
<li><input type="checkbox" name="mylistch" value="{{ pr.productid }}"></li>
<li><input type="hidden" name="mylist" value="{{ pr.productname }}"></li>
<li><input type="number" name="mylist" id="prqty"/></li>
</ul>
{% endfor %}
and View :
pch = request.POST.getlist('mylistch')
pnch = iter(pch)
pr = request.POST.getlist('mylist')
pri = iter(pr)
for pid, pname, ptotal in zip(pnch , pri , pri):
models.Sellinvoiceitems.objects.create(
productid=pid
productname=pname,
totalnumber=ptotal,
sellinvoice = invoice,
stockid = stock
)
Here i checked 5 checkbox with this ids : 6 , 9 , 10 , 12 , 19, But ids : 1 , 2 , 3 ,4 ,5 inserted to db, what is problem here?

Django - get table data from templates into views.py

I am making a restaurant application and currently working on takeaway food functionality i.e. user orders food online.
I am displaying food items from my postgresql database onto my takeaway.html template and assigning each food item a class. Each food item will have an 'add to basket' button, JavaScript provides all functionality related to the basket.
I have found some resources that mention using the GET method with a form but I'm still not too sure. I am curious as to how I can access this 'basket' in my views.py and be able to put the values into my database.
I wish to access the food name, quantity and the price from the table if possible. Any resources or help would be greatly appreciated.
takeaway.html
<div class="col-sm-12 my-auto">
<h3>Starters</h3>
{% for starter in starters %}
<div id="{{ starter.id }}">
<span class="food-item-name">{{ starter.name }}</span>
<div class="food-item-details">
<p>{{ starter.description }}</p>
<p class="food-item-price">{{ starter.price }}</p>
<p>{% for a in starter.allergen.all %}{{ a.name }} | {% endfor %}</p>
<button class="add-item-button" onclick="addToBasket(this)">Add to Basket</button>
</div>
{% endfor %}
</div>
<div>
<h3>Mains</h3>
{% for m in mains %}
<div id="{{ m.id }}">
<span class="food-item-name">{{ m.name }}</span>
<div class="food-item-details">
<p>{{ m.description }}</p>
<p class="food-item-price">{{ m.price }}</p>
<p>{% for a in m.allergen.all %}{{ a.name }} | {% endfor %}</p>
<button class="add-item-button" onclick="addToBasket(this)">Add to Basket</button>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
<div>
<h3>Basket</h3>
<form method="get">
<table id="basket" style="border: 1px solid black">
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price of Item(s)</th>
</tr>
</table>
<h3 id="basket-total-price">0.0</h3>
<button type="submit">submit</button>
</form>
</div>
takeaway.js
function addToBasket(selected)
{
const id = selected.parentElement.parentElement;
const itemName = id.getElementsByClassName("food-item-name")[0].innerText;
const itemPrice = id.getElementsByClassName("food-item-price")[0].innerText;
// check if item already in basket
if (check(itemName))
{
updateQuantity(itemName);
updateItemPrice(itemName);
}
else
{
const basketTable = document.getElementById("basket");
const rowCount = basketTable.rows.length;
const row = basketTable.insertRow(rowCount);
const basketRowName = row.insertCell(0);
const basketRowQuantity = row.insertCell(1);
const basketRowPrice = row.insertCell(2)
const basketRowTotalPrice = row.insertCell(3);
basketRowName.className = "basket-item-name";
basketRowQuantity.className = "basket-item-quantity";
basketRowPrice.className = "basket-item-price";
basketRowTotalPrice.className = "basket-item-total-price";
basketRowName.innerText = itemName;
basketRowPrice.innerText = itemPrice;
basketRowQuantity.innerText = "1";
updateItemPrice(itemName);
}
}
// check if item already in basket
function check(itemName)
{
const basketTable = document.getElementById("basket");
for(let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName)
{
return true;
}
}
}
// update quantity field for item
function updateQuantity(itemName)
{
const basketTable = document.getElementById("basket");
for(let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName){
const itemQuantity = basketTable.rows[i].getElementsByClassName("basket-item-quantity")[0];
let quantity = Number(itemQuantity.innerText);
quantity += 1;
itemQuantity.innerText = quantity;
}
}
}
// update price for item and total basket
function updateItemPrice(itemName)
{
const basketTable = document.getElementById("basket");
let itemTotal = 0;
let basketTotal = 0;
for (let i = 0; i < basketTable.rows.length; i++)
{
if (basketTable.rows[i].cells[0].innerHTML === itemName)
{
let itemPrice = basketTable.rows[i].getElementsByClassName("basket-item-price")[0];
let itemQuantity = basketTable.rows[i].getElementsByClassName("basket-item-quantity")[0];
let itemPriceTotal = basketTable.rows[i].getElementsByClassName("basket-item-total-price")[0];
let overall = document.getElementById("basket-total-price");
let current_price = parseFloat(overall.innerText);
// update price for items x quantity
itemTotal = parseFloat(itemPrice.innerText) * parseInt(itemQuantity.innerText);
itemPriceTotal.innerText = ""+ itemTotal;
// update basket total price
basketTotal = current_price + itemTotal;
overall.innerHTML = ""+basketTotal
}
}
}

Request.files 400 Bad Request in flask

flask with a project in my project I'm uploading an application I'm developing. I have 2 image upload areas. I don't have any trouble when I load 2. 400 Bad Request: KeyError: I get an error in the 'gelinFoto' style when I upload an image or when I push the send button when I never load it. Where am I making a mistake?
def admin():
form = KisiForm(request.form)
if request.method == "POST":
gelinFoto = request.files['gelinFoto']
damatFoto = request.files['damatFoto']
if gelinFoto or damatFoto:
yol = app.config['UPLOAD_FOLDER'] + whuser
yol = yol + '/profil'
gfilename = secure_filename(gelinFoto.filename)
dfilename = secure_filename(damatFoto.filename)
gelinFoto.save(os.path.join(yol, gfilename))
damatFoto.save(os.path.join(yol, dfilename))
kisi = bilgi(gelinFoto = gfilename, damatFoto = dfilename)
db.session.add(kisi)
db.session.commit()
return redirect(url_for("admin"))
return render_template("admin/index.html",form=form)
Html
<form method="post" enctype="multipart/form-data" class="col-12">
<div class="form-group">
<label for="exampleFormControlFile1">Gelinin Fotoğrafı : </label>
<div class="upload">
<img src="{{ url_for('static', filename='admin/images/upload.png') }}" class="uploadImage" alt="">{{ render_field(form.gelinFoto,id="gelinFoto",class="gdfoto",accept=".png,.jpg,.jpeg") }} </div>
<small id="emailHelp" class="form-text text-muted">Gelinin fotoğrafını yükleyiniz.</small>
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Damatın Fotoğrafı : </label>
<div class="upload"><img src="{{ url_for('static', filename='admin/images/upload.png') }}" class="uploadImage" alt="">{{ render_field(form.damatFoto,id="damatFoto",class="gdfoto",accept=".png,.jpg,.jpeg") }}
</div>
<small id="emailHelp" class="form-text text-muted">Damatın fotoğrafını yükleyiniz.</small>
In your view you have both
gelinFoto = request.files['gelinFoto']
damatFoto = request.files['damatFoto']
This is why you get that error
When the file is not provided, then there is no request.files['gelinFoto'] for example, and Python tries to look it up, but it can't cause there is no key named gelinFoto!
The simplest trick is defining theme like this:
gelinFoto = request.files.get('gelinFoto', None)
damatFoto = request.files.get('damatFoto', None)
This way it uses an inline condition to get the keys, if they are not provided, then it sets the value None
Later in your code I see you did that again,
if gelinFoto or damatFoto:
# ... Your other coders
gfilename = secure_filename(gelinFoto.filename)
dfilename = secure_filename(damatFoto.filename)
gelinFoto.save(os.path.join(yol, gfilename))
damatFoto.save(os.path.join(yol, dfilename))
It's wrong, you are checking with it with or and then u except both to be not None !!
It's better to do the operation for each one separately, like:
if gelinFoto:
yol = app.config['UPLOAD_FOLDER'] + whuser
yol = yol + '/profil'
gfilename = secure_filename(gelinFoto.filename)
gelinFoto.save(os.path.join(yol, gfilename)
if damatFoto:
yol = app.config['UPLOAD_FOLDER'] + whuser
yol = yol + '/profil'
dfilename = secure_filename(damatFoto.filename)
damatFoto.save(os.path.join(yol, dfilename)
# I'm not sure if there is a better way to do this but about kisi line This is the best that came up to me ( ofcourse there are better ways )
if gelinFoto and damatFoto:
kisi = bilgi(gelinFoto = gfilename, damatFoto = dfilename)
elif gelinFoto:
kisi = bilgi(gelinFoto = gfilename)
elif damatFoto:
kisi = bilgi(damatFoto = dfilename)

Django how to chain sorting and filtering by GET request

When I select ordering I can't really include automatically per-page filter.
How do I make these filters "visible" to each other? What do I need include or read?
That's a small part of my view.py
if order == 'asc':
p = p.order_by('name')
elif order == 'desc':
p = p.order_by('-name')
elif order == 'price_asc':
p = p.order_by('price_netto')
elif order == 'price_desc':
p = p.order_by('-price_netto')
else:
p.order_by('name')
if limit == "12":
per_page = "12"
elif limit == "24":
per_page = "24"
elif limit == "48":
per_page = "48"
else:
from endless_pagination.settings import PER_PAGE
per_page = PER_PAGE
HTML
<select onchange="location = this.options[this.selectedIndex].value">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="?order=desc">Malejąco według nazwy</option>
<option rel="order" value="?order=asc">Rosnąco według nazwy</option>
<option rel="order" value="?order=price_asc">Rosnąco według ceny</option>
<option rel="order" value="?order=price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" href="?limit=12">12</a>, <a rel="limit" href="?limit=24">24</a>, <a rel="limit" href="?limit=48">48</a>
Why not use javascript, jquery. You need a function that will read the query string and override the item you're changing.
<select id="sort-dropdown">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="desc">Malejąco według nazwy</option>
<option rel="order" value="asc">Rosnąco według nazwy</option>
<option rel="order" value="price_asc">Rosnąco według ceny</option>
<option rel="order" value="price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" id="limit-12" href="#">12</a>, <a rel="limit" id="limit-24" href="#">24</a>, <a rel="limit" id="limit-48" href="#">48</a>
Then the javascript will look like:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function redirect(order, limit) {
window.location.url = "?order=" + order + "&limit=" + limit;
}
$("#sort-dropdown").change(function () {
redirect($(this).val(), getParameterByName("limit"));
});
$("#limit-12").change(function () {
redirect(getParameterByName("order"), "12");
});
$("#limit-24").change(function () {
redirect(getParameterByName("order"), "24");
});
$("#limit-48").change(function () {
redirect(getParameterByName("order"), "48");
});

Is it possible to override form helpers?

Using the doc, I can set my own helper for the layout surrending my field, but I'd like to personalize also some fields given by play.
The main reason is for Twitter Bootstrap 2, where I need to change (in checkbox.scala.html)
#input(field, args:_*) { (id, name, value, htmlArgs) =>
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
<span>#args.toMap.get('_text)</span>
}
to :
<label class="checkbox">
<input type="checkbox" name="#name" id="#id" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
#args.toMap.get('_text)
</label>
How can I do that ?
Thanks for your help!
I finally did it like this :
I created a package views.helpers.form, that contains :
bootstrap.scala.html :
#(elements: helper.FieldElements)
<div class="control-group#if(elements.hasErrors) { error}">
<label class="control-label" for="#elements.id">#elements.label(elements.lang)</label>
<div class="controls">
#elements.input
#elements.infos(elements.lang).map { info =>
<span class="help-inline">#info</span>
}
#elements.errors(elements.lang).map { error =>
<span class="help-block">#error</span>
}
</div>
checkbox.scala.html :
#**
* Generate an HTML input checkbox.
*
* Example:
* {{{
* #checkbox(field = myForm("done"))
* }}}
*
* #param field The form field.
* #param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
* #param handler The field constructor.
*#
#(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)
#boxValue = #{ args.toMap.get('value).getOrElse("true") }
#helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
<label class="checkbox">
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
#args.toMap.get('_text)
</label>
div>
</div>
And in my template, all I have to do is :
#import helper.{FieldConstructor, inputText, inputPassword} #** Import the original helpers *#
#import helpers.form.checkbox #** Import my helpers *#
#implicitField = #{ FieldConstructor(helpers.form.bootstrap.f) }
And voilà! It works!
It will be simpler to just write your own tag with the code you want and use it instead of the provided helper. It will simplify potential issues related to overwritting platform tags.