If condition is not working in Inner Loop in django templates - python

I don't know what is the problem and I've been stuck here for hours. There maybe duplicate questions but none of them could get me out of this.
I am using an if condition in the inner loop to check if the attribute of inner is equal to the outer loop but if condition is never true even the data is same.
I've printed the data individually, both attributes print the data mean data is correct. But when I use if condition it goes to else
Data
Here's the data I'm working with:
activityy.activity_name = [Table Tennis,Swimming Pool, Football ]
slot.activity = [Table Tennis,Table Tennis,Table Tennis,Table Tennis,Swimming Pool, Football]
activities.html
{% for activityy in all_activities%}
<div style="margin-left: 450px; padding: 15px; border-radius: 5px; background-color: #dfdfdf;height: 150px; width: 800px; margin-top: 20px; text-align: center">
{% for slot in all_slots %}
{% if slot.activity == activityy.activity_name %}
<div style="background-color: #3a589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;">
<span style="color: #f1f1f1; font-size: 20px;"> {{ activityy.activity_name}}</span><br>
</div>
{% else %}
<div style="background-color: #589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;">
<span style="color: #f1f1f1; font-size: 20px;"> {{ slot.activity}}</span><br>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
Views.py
def activities(request):
if request.user.is_authenticated:
template = loader.get_template('sklc/activities.html')
slots = []
now = datetime.datetime.now()
datee = now.strftime("%Y-%m-%d")
if request.method == 'POST':
dat = request.POST['date']
if dat:
datee = dat
print("dateesss: " , datee)
activitiess = Activities.objects.all();
for activityy in activitiess:
slot = ActivitySlots.objects.filter(dates=datee).filter(activity__activity_name=activityy.activity_name)
for slott in slot:
slots.append(slott)
context = {
'all_activities': activitiess,
'all_slots': slots
}
return HttpResponse(template.render(context, request))
else:
messages.error(request, "Please Login First")
return redirect("/login")
models.py
class Activities(models.Model):
activity_name = models.CharField(max_length=50)
def __str__(self):
return self.activity_name
class ActivitySlots(models.Model):
dates = models.DateField()
available = models.BooleanField()
activity = models.ForeignKey(Activities)
time = models.CharField(max_length=50)
def __str__(self):
return self.time

I solved it by using
{% if slot.activity == activityy %}
Butt still don't know why it was not working with activityy.activity_name because activityy and activityy_activity_name are printing the same thing.

Related

how to subtract form data in django

I am developing a inventory management and I have to subtract the Quantity from 2 different forms data and display the available quantity.
Below is my views.py
def my_form2(request):
if request.method == "POST":
form2 = MyForm2(request.POST)
if form2.is_valid():
form2.save()
return HttpResponse('Submitted Successfully')
else:
form2 = MyForm2()
return render(request, "authentication/Incoming_QC.html", {'form2': form2})
def View_Incoming_QC(request):
Incoming_QC_list = Incoming_QC.objects.all()
return render(request, 'authentication/View_Incoming_QC.html',
{'Incoming_QC_list': Incoming_QC_list})
def my_form3(request):
if request.method == "POST":
form3 = MyForm3(request.POST)
if form3.is_valid():
form3.save()
return HttpResponse('Submitted successfully')
# return redirect('/home_page/')
else:
form3 = MyForm3()
return render(request, "authentication/Manufacturing.html", {'form3': form3})
def View_Manufacturing(request):
Manufacturing_list = Manufacturing.objects.all()
return render(request, 'authentication/View_Manufacturing.html',
{'Manufacturing_list': Manufacturing_list})
def my_form5(request):
if request.method == "POST":
form5 = MyForm5(request.POST)
if form5.is_valid():
form5.save()
return HttpResponse('Submitted successfully')
# return redirect('/home_page/')
else:
form5 = MyForm5()
return render(request, "authentication/Material.html", {'form5': form5})
def View_Material(request):
Material_list = Material.objects.all()
return render(request, 'authentication/View_Material.html',
{'Material_list': Material_list})
Below is the models.py
class Incoming_QC(models.Model):
alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.')
Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric])
Quantity = models.IntegerField()
class Manufacturing(models.Model):
alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.')
Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric])
Completed_Quantity = models.IntegerField(blank=True, default='')
class Material(models.Model):
alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.')
Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric])
Quantity = models.IntegerField()
.html file to view the data
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
table, th, td {
border:1px solid black;
}
body {
margin-bottom: 100px;
background-color: lightgrey;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #04AA6D;
color: white;
}
</style>
</head>
<body>
{% csrf_token %}
{% load static %}
<div class="topnav">
Home
Material Details
View Material Details
</div>
<div style="padding-left:16px">
</div>
<h1>
<center>
Material Details
</center>
</h1>
<table style="width:100%">
<thead>
<tr>
<th>Manufacturing_PN</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
{% for Material in Material_list %}
<strong> {{ Material }}</strong>
<td> {{Material.Manufacturing_PN }} </td>
<td> {{Material.Quantity}} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
SO here whenever the user submit the incoming QC and Manufacturing forms. The Quantity entered by the user in both the form or single form I want to subtract the Quantity of the Material data.
Note: The Quantity should be subtracted based on the manufacturing_PN.
It should look like below logic:
if Material.manufacturing_PN == Manufacturing.manufacturing_PN || Material.manufacturing_PN == Incoming_QC.manufacturing_PN
Material.manufacturing_PN = Material.manufacturing_PN - Incoming_QC.manufacturing_PN - Manufacturing.manufacturing_PN
It would be very helpful if someone help me out in this. Thanks in advance

django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P<pk>[0-9]+)$']

im trying to create a django page for update a dta inside database, i made this before in other projects and aways worked, but in my project it returns this error: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)$']
i reviewed my code a thousand times and i can't see nothing wrong, even if comparing with the other projects.
Obs.: please ignore the css part of my template, i'm not used to write the css inside the html, but as it's just a test i don't create a external file.
urls.py:
from django.urls import path
import tables1.views as vw
urlpatterns = [
path('admin/', admin.site.urls, name = 'admin'),
path('mytables/', vw.mytables, name = 'mytables'),
path('',vw.home),
path('table/<int:pk>',vw.table, name = 'tableurl'),
path('newtable/',vw.newtable,name = 'newtable'),
path('update/<int:pk>',vw.update,name = 'update'),
path('delete/<int:pk>',vw.delete,name = 'delete'),
path('new/',vw.new, name = 'newurl')
]
models.py:
class Table(models.Model):
idd = models.AutoField(primary_key=True, default=None)
name = models.CharField(max_length=100)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Tables'
def __str__(self):
return self.name
class Transacao(models.Model):
# Forein key defined here
date = models.DateTimeField(auto_now_add=True)
desc = models.CharField(max_length=200)
value = models.DecimalField(max_digits=7, decimal_places=2)
obs = models.TextField(null=True, blank=True)
tableid = models.CharField(max_length=3)
class Meta:
verbose_name_plural = 'Transacoes'
def __str__(self):
return self.desc
views.py:
from .models import Table
from .models import Transacao
from .forms import TableForm
from .forms import TransacaoForm
def home(request):
now = {}
return render(request,'tables1/home.html',now)
def mytables(request):
data = {}
data['tables'] = Table.objects.all()
return render(request, 'tables1/mytables.html', data)
def update(request,pk):
transacao = Transacao.objects.get(pk = pk)
form = TransacaoForm(request.POST or None, instance=transacao)
if form.is_valid():
form.save()
return render(request,'tables1/new.html',{'form':form})
def new(request):
form = TransacaoForm(request.POST or None)
if form.is_valid():
form.save()
return render(request,'contas/form.html',{'form':form})
def delete(request,pk):
transacao = Transacao.objects.get(pk = pk)
transacao.delete()
return redirect('lists')
def table(request,pk):
form = TransacaoForm(request.POST or None)
data = Table.objects.get(idd = pk)
lists = Transacao.objects.filter(tableid = pk)
if request.method == 'POST':
if form.is_valid():
formdesc = form.cleaned_data['desc']
formvalue = form.cleaned_data['value']
transaction_instance = Transacao.objects.create(desc = formdesc,value = formvalue,tableid = pk)
return render(request,'tables1/table.html',{'data':data, 'form':form, 'lists':lists})
def newtable(request):
form = TableForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('mytables')
return render(request,'tables1/newtable.html',{'form':form})
table.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box;}
/* Button used to open the contact form - fixed at the bottom of the page */
.open-button {
background-color: #555;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
opacity: 0.8;
}
/* The popup form - hidden by default */
.form-popup {
display: none;
bottom: 0;
right-margin: 10px;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
}
/* Add styles to the form container */
.form-container {
max-width: 300px;
padding: 10px;
background-color: white;
}
/* Full-width input fields */
.form-container input[type=text], .form-container input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Set a style for the submit/login button */
.form-container .btn {
background-color: #4CAF50;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {
opacity: 1;
}
</style>
</head>
<body>
<h1>{{data}}</h1>
<table id = tabela>
<tr>
<th>Item</th>
<th>Data e Hora</th>
<th>Valor</th>
</tr>
{% for list in lists %}
<tr>
<td>{{list.desc}}</td><td>{{list.date}}</td>
<td>{{list.value}}</td><td>{{list.categ}}</td>
<td><form action="{% url 'update' transacao.id %}">
<button type="submit"><b>Editar</b></button>
</form></td>
<td><form action="{% url 'delete' transacao.id %}">
<button type="submit"><b>Excluir</b></button>
</form></td>
</tr>
{%endfor%}
</table>
<button class="open-button" onclick="{% url newurl %}">Nova Transação</button>
<form method="post" class="form-container">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn" onclick="location.reload()">Login</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</body>
</html>
transacao is not a variable in your template, you use list as a variable for a Transacao object, therefore you should use {% url 'update' list.id %} and {% url 'delete' list.id %}:
{% for list in lists %}
<tr>
<td>{{ list.desc }}</td><td>{{ list.date }}</td>
<td>{{ list.value }}</td><td>{{ list.categ }}</td>
<td><form action="{% url 'update' list.id %}">
<button type="submit"><b>Editar</b></button>
</form></td>
<td><form action="{% url 'delete' list.id %}">
<button type="submit"><b>Excluir</b></button>
</form></td>
</tr>
{%endfor%}
That being said, since your lists is not a collection of lists - it is a QuerySet of Transacaos - it might be better to rename lists to transacaos and use transacao as "enumerator".

jinja2.exceptions.UndefinedError is undefined

I had a problem with this jinja2.exception and I was totally confused why. I wanted to post data to my .html, which I got from an API.
#app.route("/playerstats", methods = ["GET"])
def statsget():
return render_template("stats.html")
#app.route("/playerstats", methods = ["POST"])
def statspost():
player_uri = "https://www.balldontlie.io/api/v1/players?search={}%20{}"
playerinput = request.form["nm"]
player_split = playerinput.split()
vn = player_split[0]
nn = player_split[1]
r = requests.get(player_uri.format(vn, nn)).json()
data = {
"player_id": r["data"][0]["id"],
"player_first_name": r["data"][0]["first_name"]
}
return render_template("stats.html", data=data)
<button type="button" class="btn btn-outline-secondary" style="height: 40px; width: 450px; margin-top: 5px; margin-bottom: 5px; border-width: 1px; border-color:lightgrey; text-align: start;">
{{data.player_first_name}} {{data.player_id}}
</button>
Running the webpage put out this exception: jinja2.exceptions.UndefinedError 'data' is undefined
My solution was to put the data I get from the api into an array and run a for-loop inside the html to give out all data:
inside main.py:
#app.route("/playerstats", methods = ["GET"])
def pstatsget():
return render_template("stats.html")
#app.route("/playerstats", methods = ["POST"])
def pstatspost():
player_uri = "https://www.balldontlie.io/api/v1/players?search={}%20{}"
playerinput = request.form["nm"]
player_split = playerinput.split()
vn = player_split[0]
nn = player_split[1]
r = requests.get(player_uri.format(vn, nn)).json()
data_group = []
data = {
"player_id": r["data"][0]["id"],
"player_first_name": r["data"][0]["first_name"]
}
data_group.append(data)
print(data_group)
return render_template("stats.html", data=data_group)
inside stats.html:
{% for d in data: %}
<button type="button" class="btn btn-outline-secondary" style="height: 40px; width: 450px; margin-top: 5px; margin-bottom: 5px; border-width: 1px; border-color:lightgrey; text-align: start;">
{{d.player_first_name}} {{d.player_id}}
</button>
{% endfor %}
I hope this works for you aswell!

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 %}

Vertical Scroll bar django-tables2

Can anyone tell me how to add a vertical scroll bar to django-tables2 instead of having
Page 1 of 2 Next 25 of 49 vehicles
at the bottom of the table.
tables.py
'''
Created on 28 Oct 2016
#author: JXA8341
'''
import django_tables2 as tables
from .models import Vehicle
class CheckBoxColumnWithName(tables.CheckBoxColumn):
#property
def header(self):
return self.verbose_name
class VehicleTable(tables.Table):
update = tables.CheckBoxColumn(accessor="pk",
attrs = { "th__input":{"onclick": "toggle(this)"}},
orderable=False)
class Meta:
model = Vehicle
fields = ('update', 'vehid')
# Add class="paleblue" to <table> tag
attrs = {'class':'paleblue'}
screen.css
table.paleblue + ul.pagination {
font: normal 11px/14px 'Lucida Grande', Verdana, Helvetica, Arial, sans- serif;
overflow: scroll;
margin: 0;
padding: 10px;
border: 1px solid #DDD;
list-style: none;
}
div.table-container {
display: inline-block;
position:relative;
overflow:auto;
}
table.html
<div class='vehlist'>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('update');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
<form action="/loadlocndb/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% render_table veh_list %}
<h4> Location database .csv file</h4>
{{ form.locndb }}
<input type="submit" value="Submit" />
</form>
</div>
I've looked all over but I can't seem to get a straight answer, or is there a better table module I can use to display the array and checkboxes?
For anyone in the same boat I figured it out.
I turned disabled pagination
RequestConfig(request, pagination=False).configure(veh_list)
then I wrapped the table in a <div> in the html template
<div style="width: 125px; height: 500px; overflow-y: scroll;">
{% render_table veh_list %}
</div>
The <div> then adds a scrollbar to the whole table interface, I personally would have liked to keep the header constantly at the top but this is the best solution I could come up with.

Categories

Resources