How do I set value to hidden integerfield in WTForms - flask

I have a form which needs to take in 1 integer value. This integer value will be an id associated with a row in a html table.
template.html
{% block content %}
<div id="formContainer" class="center top">
<p class="lead">Select simulation session </p>
{% if simulationSessions %}
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>#</th>
<th>Label</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{% for simulationSession in simulationSessions %}
<tr>
<td><input id="id-{{ simulationSession.id }}" name="idRadio" type="radio" value="{{ simulationSession.id }}"> </td>
<td>{{ simulationSession.id }}</td>
<td>{{ simulationSession.label }}</td>
<td>{{ simulationSession.date.strftime('%d-%m-%y %H:%M') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="button" class="btn btn-sm btn-success">Analyse</button>
{% else %}
<div class="alert alert-danger" role="alert">
<strong>Oopsadazy!</strong> No simulations are registered in the database for this user. You need to run a simulation session before analyzing it!
</div>
{% endif %}
</div>
{% endblock %}
Each table row has a radio button, and the value from the selected button will be the only thing my form requires. I have decided to go with one hidden IntegerField instead of a RadioField. It is possible to do the latter but then I have to solve the problem of dynamically creating the choices (I decided to go against that when I couldn't pass the list as a parameter when referencing the form from my view.py).
form.py
class SimulationSessionSelectionForm(Form):
simulationSessoinId = IntegerField('simulationSessoinId', validators=[DataRequired()], widget=HiddenInput())
My questions is how can I take the value from the selected radio button and use that as the data for the hidden integer field once the form is submitted?
This could maybe be done with something similar to this inside a script within the html? (this does not compile)
{% set form.id.data %}
this.value
{% endset %}
The view would look something like this:
view.py
#app.route('/dashboard', methods=['GET', 'POST'])
#login_required
def dashboard():
form = SimulationSessionSelectionForm()
if form.validate_on_submit():
redirect('/somewhere')
userkey = models.User.query.filter_by(id = current_user.get_id()).first().userKey
userSimulationSessions = models.SimulationSession.query.filter_by(userKey = userkey).all()
simulationSessions = []
simulationSessionIds = []
for simulation in userSimulationSessions:
simulationSessions.append({'id' : simulation.sessionID, 'label' : simulation.label, 'date' : simulation.date})
simulationSessionIds.append(simulation.sessionID)
return render_template("dashboard.html", simulationSessions = simulationSessions, form = form)

This line in the template adds the hidden field (and the csfr token) to the
{{ form.hidden_tag() }}
I figured I could just set the value of the hidden IntegerField by some jquery script whenever the radio button change event fired. To do this I used the following code:
<script>
$( document ).ready(function() {
$('input[type=radio][name=idRadio]').change(function() {
$('#simulationSessoinId').val(this.value)
});
});
</script>

Related

How to hide entire row if one or two fields are empty Django

How can I hide an entire row if one or more specific fields are empty? For example, I have a django query set up so that I can get a total profit from items in the inventory manager. The way that I have that written is like:
html
{% extends 'portal/base.html' %}
{% block title %}Inventory{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<form class="d-flex" role="search" action="/search" method="get">
<input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success">Search</button>
</form>
</div>
<div class="col">
<a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Breakdown</th>
<th>Product ID</th>
<th>Product</th>
<th>Total Profit</th>
</tr>
</thead>
{% for inventory in inventory %}
<tr>
<td><a class='btn btn-success btn-sm' href=''>View Breakdown</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{ inventory.Calculate_profit }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
views.py
#login_required(login_url="/login")
def profitsperitem(request):
inventory = Inventory.objects.all().order_by('id')
return render(request, 'portal/profitsperitem.html', {"inventory": inventory})
models.py
#property
def Calculate_profit(self):
soldfor = Inventory.objects.filter(soldprice=self.soldprice).aggregate(Sum('soldprice'))['soldprice__sum'] or 0.00
paidfor = Inventory.objects.filter(paid=self.paid).aggregate(Sum('paid'))['paid__sum'] or 0.00
shipfor = Inventory.objects.filter(shipcost=self.shipcost).aggregate(Sum('shipcost'))['shipcost__sum'] or 0.00
totalprofit = soldfor - paidfor - shipfor
return totalprofit
As long as the model fields soldprice , paid , and shipcost are all filled out on every row in the database, I can get the results no problem. I get an error if soldprice or shipcost are null or none, so when there is nothing added to database. If one row does not have soldprice or shipcost set, none of the results can be viewed as this error pops up: "TypeError at /profitsperitem
unsupported operand type(s) for -: 'float' and 'decimal.Decimal'"
My question is how can I hide the entire row if either or both soldprice and/or shipcost are empty?
Tho filter all rows with any of the two fields beeing null/None use a query like this
from django.db.models import Q
#login_required(login_url="/login")
def profitsperitem(request):
inventory = Inventory.objects.filter(
Q(soldprice__isnull = False) | Q(shipcost__isnull = False)
).order_by('id')
return render(request, 'portal/profitsperitem.html', {"inventory": inventory})
I was able to update the view like this
#login_required(login_url="/login")
def profitsperitem(request):
inventory = Inventory.objects.filter(soldprice__isnull = False, shipcost__isnull = False).order_by('id')
return render(request, 'portal/profitsperitem.html', {"inventory": inventory})
{% for inventory in inventory %}
{% if inventory.Calculate_profit %}
<tr>
<td><a class='btn btn-success btn-sm' href=''>View Breakdown</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{ inventory.Calculate_profit }}</td>
</tr>
{% endif %}
{% endfor %}
you can print row only if you have calculate price.
if(soldfor is not None and paidfor is not None and shipfor is not None )
totalprofit = soldfor - paidfor - shipfor
else totalprofit =None
Also You can check if Calculate profit has some value

Bootstrap Table not sending selected checkbox values in POST request in Django app

I am using Bootstrap Table (https://bootstrap-table.com/) to display a product list in a Django app. I would like the user to select some products and click the button to submit. Using Bootstrap Table seems to prevent the checked checkboxes being sent in the POST request.
views.py
class ProductProcessView(View):
def post(self, request):
products = request.POST.getlist('product_checkboxes')
# process the chosen products
return redirect('product-list')
html template
<form method="post">
{% csrf_token %}
<table class="table-striped"
data-toggle="table"
>
<thead>
<tr>
<th data-field="product_id" data-checkbox="true"></th>
<th data-field="product">Product</th>
</tr>
</thead>
{% for product in product_list %}
<tr>
<td><input type="checkbox" name="product_checkboxes" value="{{ product.id }}"></td>
<td>{{ product.short_name }}</td>
</tr>
{% endfor %}
</table>
<button onclick="location.href='{% url 'process-products' %}'">Select Products</button>
</form>
If I remove the line data-toggle="table" this correctly sends the selected product IDs in the POST request, but with that line included it does not send any IDs at all. Bootstrap Table requires the data-toggle="table" attribute to initialise the table so without it there is no formatting.
This is the request.body with data-toggle="table" included:
<QueryDict: {'csrfmiddlewaretoken': ['fOma6gtvG2ETw1hrVYMdIuSUWuE1RA2jpX2Tae7ntipMPGX4yKNYEGgkHD0Jcuco'], 'btSelectItem': ['on', 'on']}>
This is without it:
<QueryDict: {'csrfmiddlewaretoken': ['Si6UyiTZ4yAJNYKKQ9FtA8dk0gNPGTPp2rMDCgxRROlC6DqntVGewkBKLp9x1NZu'], 'product_checkboxes': ['43004', '43006']}>
I would be very grateful for any ideas about how I can use the Bootstrap Table framework with it's formatting and widgets, but still be able to use checkboxes to collect the product data.
You can't rely on your HTML because it is dynamically replaced by BootstrapTable.
So you need to use its API to retrieve the values. The simplest way is to add script to the page which will get values from table and assign on some (hidden) element in the form.
Then - on Python side you will read this field and process the data.
See example (uses JQuery but can be converted to plain JS):
<script>
$(document).ready(function () {
$('#product-form').on('submit', function () {
const table = $('#products').bootstrapTable('getSelections')
$('#checkboxes').val(JSON.stringify(table))
})
})
</script>
Some corrections to the template:
Add ID to form
Include product ID as hidden column
Add hidden element which will pass content via form
html template:
<form method="post" id="product-form">
{% csrf_token %}
<table id="products" class="table-striped" data-toggle="table">
<thead>
<tr>
<th data-field="product_check" data-checkbox="true"></th>
<th data-field="product_id" data-visible="false">ID</th>
<th data-field="product">Product</th>
</tr>
</thead>
<input id="checkboxes" name="product_checkboxes" style="display: none">
{% for product in product_list %}
<tr>
<td><input type="checkbox" data-id="{{ product.id }}" value="{{ product.id }}"></td>
<td>{{ product.id }}</td>
<td>{{ product.short_name }}</td>
</tr>
{% endfor %}
</table>
<button id="select-products" onclick="location.href='{% url 'process-products' %}'">Select Products</button>
</form>
And finally - getting the data in views.py:
def post(self, request):
products = json.loads(request.POST.get('product_checkboxes'))
# process the chosen products
return redirect('product-list')
Note that in this case products will be a list of objects. Each object has values that are correspondent to columns

Django Form Not Validating my Date fields

I have a Search form that includes the query box, some checkbox items, and a start and end date. I am getting my information when I enter a query, so I know it is performing the search_results action, but the start and end date is not getting validated at all. I have yet to add the code to handle the start and end date in my results, but the issue is there is no client side validation happening on the form.
My form looks like this:
class SearchForm(forms.Form):
q = forms.CharField(max_length=64,required=False)
service_choices = forms.MultipleChoiceField(
required=True,
widget=forms.CheckboxSelectMultiple,
choices=CustomUser.SERVICE_CHOICES,
)
start_date = forms.DateField(required=False)
end_date = forms.DateField(required=False)
I tried using Class Based View, but did not get any fields at all, so I
tried using a function based view to get my search criteria.
The view looks like:
def get_search(request):
form = SearchForm()
return render(request, 'get_search.html', {'form':form})
My template is:
<!-- templates/get_search.html -->
{% extends "base.html" %}
{% block title %}Search{% endblock title %}
{% block content %}
{% if user.is_authenticated %}
<br><br>
<TABLE BORDER="0" WIDTH="100%">
<TR>
<TD ALIGN="Left"><B>Track X - search</B></TD>
<TD ALIGN="Center"><B>User: {{ user }}</B></TD>
<TD ALIGN="Right"><B>Service: {{ user.service }}</B></TD>
</TR>
</TABLE>
<form action="{% url 'search_results' %}" method="get"">
{% csrf_token %}
<TABLE BGCOLOR="#66CCCC" Border="2" WIDTH="100%">
<TR>
<TD ALIGN="Left" WIDTH="100"> Services:</TD>
<TD ALIGN="Right">Search expression:</TD>
<TD ALIGN="Left">
{{ form.q }}
<button type="submit" name="submit">Search TrackX</button>
</TD>
</TR>
<TR>
<TD WIDTH="100"> {{ form.service_choices }} </TD>
<TD COLSPAN="2" ALIGN="Center"> Start Date: {{ form.start_date }}
End Date: {{ form.end_date }}</TD>
</TR>
</TABLE>
</form>
{% else %}
<p>You are not logged in</p>
Log In |
Sign Up
{% endif %}
{% endblock content %}
The Search_results view just uses the query to build some Q Filter
queries, and it seems to be working correctly.
It originally used a GET Method, and was passing the parameters into the search results view just fine. It just doesn't validate the dates (or anything else I assume) before passing the parameters into the view.
Can anyone tell me what am I missing here?
As I see on the view that your posted, you are not actually checking if the form is valid, you can do that by using:
if request.method == 'POST':
form = SearchForm(request.POST)
form.is_valid()
This method will validate all your fields, and return the boolean value representing if its valid or not.

Django - How to delete a object directly from a button in a table

(sorry for my bad english)
I need to delete an object, but directly from a list of the objects that y have in my template.
I have a work orders, that have spare parts but i don't know how to create the deleteview for the spare parts using only a buton in the detailview of the work order. The idea is that the user make click in the Delete button.
This is the model of the Spare Parts
class OrderSparePart(models.Model):
# Relations
workorder = models.ForeignKey(
WorkOrder,
verbose_name=_('order'),
)
# Attributes - Mandatory
spare_part = models.CharField(
max_length=80,
verbose_name=_('spare part'),
)
# Attributes - Optional
price = models.DecimalField(
max_digits=6,
decimal_places=2,
null=True,
blank=True,
verbose_name=_('price'),
)
# Object Manager
# Custom Properties
# Methods
def get_absolute_url(self):
return reverse('work_orders:detail', kwargs={'order_id': self.workorder.id})
# Meta and String
class Meta:
verbose_name = _("order spare part")
verbose_name_plural = _("order spare parts")
This is where is showed in the template
{% if spare_parts %}
<table class="table">
<thead>
<tr>
<th>{% trans "Spare Part" %}</th>
<th>{% trans "Price" %}</th>
<th>{% trans "Delete" %}</th>
</tr>
</thead>
<tbody>
{% for part in spare_parts %}
<tr>
<td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
{% if part.price %}
<td>$ {{ part.price }}</td>
{% else %}
<td></td>
{% endif %}
<td><i class="fa fa-trash"></i></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>NO HAY REPUESTOS ASENTADOS AÚN</p>
{% endif %}
The the idea is use the to delete the spare part.
how i have to make the deleteview and the link to this???
Thanks!
here in fa fa-thrash pass the id and the URL as I did it:-
{% if spare_parts %}
<table class="table">
<thead>
<tr>
<th>{% trans "Spare Part" %}</th>
<th>{% trans "Price" %}</th>
<th>{% trans "Delete" %}</th>
</tr>
</thead>
<tbody>
{% for part in spare_parts %}
<tr>
<td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
{% if part.price %}
<td>$ {{ part.price }}</td>
{% else %}
<td></td>
{% endif %}
<td></i></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>NO HAY REPUESTOS ASENTADOS AÚN</p>
{% endif %}
ur url would be sonething like that:
url(r'^delete/(?P<part_id>[0-9]+)/$', view.function, name='delete_view'),
in ur view:
def function(request,part_id =None):
object = YourModel.objects.get(id=part_id)
object.delete()
return render(request,'ur template where you want to redirect')
In your html template inside for loop use the form tag inside <td> to create delete button as below (css class will work if you are using bootstrap3):
<form action="{% url 'delete_view' pk=part.pk %}" method="POST">
{% csrf_token %}
<input class="btn btn-default btn-danger" type="submit" value="Delete"/>
</form>
add urlpattern in urls.py
url(r'^delete-entry/(?P<pk>\d+)/$', views.DeleteView.as_view(), name='delete_view'),
delete view will be like below in views.py
class DeleteView(SuccessMessageMixin, DeleteView):
model = OrderSparePart
success_url = '/'
success_message = "deleted..."
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
name = self.object.name
request.session['name'] = name # name will be change according to your need
message = request.session['name'] + ' deleted successfully'
messages.success(self.request, message)
return super(DeleteView, self).delete(request, *args, **kwargs)
Note: import necessary imports shown in links or you need not to worry if you are using IDE such as pyCharm it will prompt you which import to make.
My solutions works best for django 4.0.3 and is the combination of gahan and Abi waqas answers. Use this one if you are using django 3 or above
Add the following to views.py
def delete_object_function(request, id):
# OrderSparePart is the Model of which the object is present
ob = OrderSparePart.objects.get(id=id)
ob.delete()
return redirect('page-delete.html') # for best results, redirect to the same page from where delete function is called
Add the following to urls.py
path('page-delete/<int:id>', views.delete_object_function, name='delete_object'),
Add the following code to the django template from where the delete function is to be called.
Let's say page-delete.html
<form action="{% url 'delete_object' id=part.id %}" method="post">
{% csrf_token %}
<button class="btn btn-danger" type="submit" ><i class="fa fa-trash"></i></button>
</form>
This works as I've used this solution in my own code.

model object not iterable

template.html
{% extends "base.html" %}
<body>
{% block content %}
<form action="." method="post">
{% csrf_token %}
<table align="center" style="margin-left:60px";>
<p>{{KEBReading_form.as_table}}</p>
<tr><td colspan="2" align="right"><input name="KEBsubmit" type="submit" value="Submit Reading" id="_KEBsubmit1"/> </td></tr>
<tr><td colspan="2" >{{KEBMessage}} </td></tr>
</table>
</form>
<table border="1">
<p> KEB Reading as on Month jan and year 2012</p>
<tr>
<th>Date </th>
<th>Time</th>
<th>True Power Reading</th>
<th>Apparent Power Reading</th>
<th>True Power consumed</th>
<th>Voltage Reading</th>
<th>Power Factor</th>
</tr>
{% for item in q2 %}
<tr>
<td>{{item.date}}</td>
<td>{{item.time}}</td>
<td>{{item.truepower_reading}}</td>
<td>{{item.apparentpower_reading}}</td>
<td>{{item.truepower_consumed}}</td>
<td>{{item.voltage_reading}}</td>
<td> {{item.powerfactor}}</td>
</tr>
{% endfor %}
</table>
{% endblock content %}
views.py
def KEBReading1(request):
#form2 = KEBReading.objects.all()
if request.method == "POST":
form = KEBReading_form(request.POST)
if form.is_valid():
prevdate=KEBReading.objects.latest("date")
# Model.objects.latest('field')
print prevdate.date
print prevdate.time
# q1 = KEBReading.objects.get(datetime.date.today()-datetime.timedelta(0))
kr_truepower_reading = form.cleaned_data["truepower_reading"]
kr_apparentpower_reading = form.cleaned_data["apparentpower_reading"]
truepower_consumed1=kr_truepower_reading-prevdate.truepower_reading
powerfactor1=((kr_truepower_reading-prevdate.truepower_reading)/(kr_apparentpower_reading-prevdate.apparentpower_reading))
#instance=truepower_consumed,powerfactor
## replace form.save() with following lines
form1=form.save(commit=False)
#form1.calculate(truepower_consumed1,powerfactor1)
form1.truepower_consumed=truepower_consumed1
form1.powerfactor=powerfactor1
print form1.powerfactor
form1.save()
q2=KEBReading.objects.latest("date")
context={'KEBReading_form':form,'q2':q2}
return render_to_response('keb.html',context,context_instance=RequestContext(request))
else:
form = KEBReading_form()
return render_to_response('keb.html',{'KEBReading_form':form},context_instance=RequestContext(request))
i want to display all readings in a table whic i calculated through the views in the template. i get model object not iterable while using for loop to iterate..
A few issues:
First, as Aidan correctly noted KEBReading.objects.latest("date") this will return an object, not a collection or iterable.
Secondly, you aren't assigning any of the fields that you are calculating in view. truepower_consumed1=kr_truepower_reading-prevdate.truepower_reading doesn't assign it to your object that you retrieved (your q2). I'm not sure if this is intentional. However, I suspect you want to return to your template the instance of the form, not another record from the table. You need to update your question.
To fix these problems immediately:
<tr>
<td>{{q2.date}}</td>
<td>{{q2.time}}</td>
<td>{{q2.truepower_reading}}</td>
<td>{{q2.apparentpower_reading}}</td>
<td>{{q2.truepower_consumed}}</td>
<td>{{q2.voltage_reading}}</td>
<td> {{q2.powerfactor}}</td>
</tr>
latest() returns the latest object in the table, not a set of objects. Instead of that, you should use KEBReading.objects.all().order_by('date')
Your q2 variable is just an object not a set.
The following line returns a single object -
KEBReading.objects.latest("date")
But your template is expecting a set that it can iterate over -
{% for item in q2 %}
<tr>
<td>{{item.date}}</td>
<td>{{item.time}}</td>
<td>{{item.truepower_reading}}</td>
<td>{{item.apparentpower_reading}}</td>
<td>{{item.truepower_consumed}}</td>
<td>{{item.voltage_reading}}</td>
<td> {{item.powerfactor}}</td>
</tr>
{% endfor %}
Check the docs for the latest() function.