This is the page that I'm trying to work out. If the update is clicked, the filled-in details should be updated in a MySql database called TL.
But while clicking update, it's throwing the following error: AttributeError at /add/
'QuerySet' object has no attribute 'save'
The following is Views.py file in Django where I had put code for add:
def add(request):
ad = TL.objects.all()
if request.method == 'POST':
TL_Name = request.POST.get('TL_Name')
Proj_name = request.POST.get('Proj_name')
Deadline = request.POST.get('Deadline')
ad.TL_Name = TL_Name
ad.Proj_name = Proj_name
ad.Deadline = Deadline
ad.save()
return redirect("/operations")
return render(request, 'operations.html', {"name": ad, 'b': ad})
The following is the urls.py file:
from . import views
urlpatterns = [
path('', views.home),
path('adminlogin/', views.adminlogin),
path('operations/', views.operations),
path('approve/<int:pk>', views.approval),
path('decline/<int:pk>/', views.delete),
path('edit/<int:pk>/', views.edit),
path('add/', views.add),
path('tlist/', views.approved_tlist)
]
The following is the operations.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Team Leaders</title>
</head>
<body>
<h1>List of Team Leaders</h1>
<table id="table">
<tr>
<th>TL_Name</th>
<th>Proj_name</th>
<th>Proj_Status</th>
<th>Deadline</th>
<th>Action</th>
</tr>
{% for i in name %}
<tr>
<td>{{i.TL_Name}}</td>
<td>{{i.Proj_name}}</td>
<td>{{i.Proj_Status}}</td>
<td>{{i.Deadline}}</td>
<td>
Approve
Decline
Edit
</td>
</tr>
{% endfor %}
</table>
<br>
<br>
{% if a %}
<form method="post">
{% csrf_token %}
<table>
<tr>
<td>
<label>TL_Name</label>
</td>
<td>
<input type="text" name="TL_Name" value="{{a.TL_Name}}">
</td>
</tr>
<tr>
<td>
<label>Proj_Name</label>
</td>
<td>
<input type="text" name="Proj_name" value="{{a.Proj_name}}">
</td>
</tr>
<tr>
<td>
<label>Proj_Status</label>
</td>
<td>
{{a.Proj_Status}}
</td>
</tr>
<tr>
<td>
<label>Deadline</label>
</td>
<td>
<input type="text" name="Deadline" value="{{a.Deadline}}">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
{% endif %}
<tr>
Add
</tr>
{% if b %}
<form method="post">
{% csrf_token %}
<table>
<tr>
<td>
<label>TL_Name</label>
</td>
<td>
<input type="text" name="TL_Name" value="{{b.TL_Name}}">
</td>
</tr>
<tr>
<td>
<label>Proj_Name</label>
</td>
<td>
<input type="text" name="Proj_name" value="{{b.Proj_name}}">
</td>
</tr>
<tr>
<td>
<label>Proj_Status</label>
</td>
<td>
{{b.Proj_Status}}
</td>
</tr>
<tr>
<td>
<label>Deadline</label>
</td>
<td>
<input type="text" name="Deadline" value="{{b.Deadline}}">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
{% endif %}
</body>
</html>
Please help me to sort out this error. Thank you in advance...
ad = TL.objects.all()
is assigning the queryset of all TL to ad
ad.TL_Name = TL_Name
ad.Proj_name = Proj_name
ad.Deadline = Deadline
ad.save()
This code will not work as this isn't a single instance of a model.
If you want update all objects of TL you can use update
ad = TL.objects.update(TL_Name=TL_Name, Proj_name=Proj_name, Deadline=Deadline)
or use TL.objects.first() or TL.objects.get(id=id_you_want)
to get an individual instance of the model and then use
ad.TL_Name = TL_Name
ad.Proj_name = Proj_name
ad.Deadline = Deadline
ad.save()
You first set ad = TL.objects.all() This returns all your Model objects. Then later on in your code you're trying to save ad to your database. That won't work, and Django is telling you that. You're trying to save a queryset.
You have this error because you apply a .save() method on a queryset, that is wrong. Instead you need to call .save() on a object instance like this:
def add(request):
# ad = TL.objects.all() Not usefull here
context = {}
if request.method == 'POST':
TL_Name = request.POST.get('TL_Name')
Proj_name = request.POST.get('Proj_name')
Deadline = request.POST.get('Deadline')
# Create a new TL instance here (Note that with class.objects.create() we don't need to call save())
new_tl = TL.objects.create(TL_Name=TL_Name, Proj_name=Proj_name, Deadline=Deadline)
# Update the context data
context = ['b'] = new_tl
return redirect("/operations")
# Retrieve all TL objects and add to context
context['name'] = TL.objects.all()
return render(request, 'operations.html', context)
Related
hello I am trying to do a multiplication in Django from models multiplying the quantity by the unit_price and reflecting the result in total_price) but I see that it is not reflected in my HTML template (I have some inputs and in the input where I want to reflect the result of the multiplication, it does not appear), does anyone know what is missing for me?
I should also mention that it is a form and a formset to which I want to apply that
models.py
class Parte(models.Model):
codigo=models.IntegerField()
quantity=models.IntegerField()
unit_price=models.IntegerField()
total_price=models.IntegerField()
tax_free=models.BooleanField()
descripcion=models.CharField(max_length=255,blank=True, null=True)
descuento=models.IntegerField()
total=models.IntegerField()
#property
def total_prices(self):
return self.quantity*self.unit_price
def __str__(self):
return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_prices} {self.tax_free}{self.descuento}{self.total}'
Parte\views.py
def create_Parte(request):
form=ParteForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('parte:index')
return render(request,'Parte/parte-form.html',{'form':form})
Presupuestos\views.py
#Create your views here.
def create_Presupuestos(request):
extra_forms = 0
ParteFormSet = formset_factory(ParteForm, extra=extra_forms, max_num=20)
formset = ParteFormSet()
presupuestosparteform=PresupuestosParteForm(request.POST or None)
if request.method == 'POST':
pass
if presupuestosclientesform.is_valid():
presupuestosclientesform.save()
return redirect('presupuestos:index')
return render(request,'Presupuestos/presupuestos-forms.html',{'presupuestosparteform':presupuestosparteform,'formset':formset})
presupuestos-forms.html
<table class="table table-bordered table-nowrap align-middle">
<thead class="table-info">
<tr>
<th scope="col">Código</th>
<th scope="col">Descripción</th>
<th scope="col">Cantidad</th>
<th scope="col">Precio Unitario</th>
<th scope="col">Precio Total</th>
<th scope="col">Libre de Impuestos</th>
<th scope="col">Agrega Fila</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{{presupuestosparteform.codigo}}
</td>
<td>
{{presupuestosparteform.descripcion}}
</td>
<td>
{{presupuestosparteform.quantity}}
</td>
<td>
{{presupuestosparteform.unit_price}}
</td>
<td>
{{presupuestosparteform.total_prices}}
</td>
<td>
<div>
{{presupuestosparteform.tax_free}}
</div>
</td>
<td>
<input type="button" class="btn btn-block btn-default" id="add_more" value="+" />
</td>
</tr>
{{ formset.management_form }}
{% for form in formset %}
<tr id="formset" class="form-row">
<td>
{% render_field form.codigo class="form-control" %}
</td>
<td>
{% render_field form.descripcion class="form-control" %}
</td>
<td>
{% render_field form.quantity class="form-control" %}
</td>
<td>
{% render_field form.unit_price class="form-control" %}
</td>
<td>
{% render_field form.total_prices class="form-control" %}
</td>
<td>
{% render_field form.tax_free class="form-check-input" %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!--el row duplicado en el formset con empty-row-->
<div class="form-row" id="empty-row">
<table class="table table-bordered table-nowrap align-middle table-formset">
<td>
{% render_field formset.empty_form.codigo class="form-control" %}
</td>
<td>
{% render_field formset.empty_form.descripcion class="form-control" %}
</td>
<td>
{% render_field formset.empty_form.quantity class="form-control" %}
</td>
<td>
{% render_field formset.empty_form.unit_price class="form-control" %}
</td>
<td>
{% render_field formset.empty_form.total_prices class="form-control" %}
</td>
<td>
{% render_field formset.empty_form.tax_free class="form-check-input" %}
</td>
</table>
</div>
I have an HTML page with a form compiled yet with default values as a modify form, in python program i want to get the modified information, if there are. i have a ID to use for update the data in my DB with pymssql. When i get data from the form in HTML page, the ID it's get, but the CF block the program and give me the error: POST/[name_page] HTTP/1.1" 400
PYTHON
#app.route('/salva_modifiche_paziente',methods=['POST'])
def dati_paziente_modificato():
id = dett_id_paz()
cf = request.form.get['cf']
nome = request.form['nome']
cognome = request.form['cognome']
data_nascita = request.form['data_nascita']
residenza = request.form['residenza']
grado_dolore = request.form['grado_dolore']
sintomi = request.form['sintomi']
data_ricovero = request.form['data_ricovero']
data_dimissione = request.form['data_dimissione']
reparto = request.form['reparto']
n_stanza = request.form['n_stanza']
n_letto = request.form['n_letto']
modifica_paziente(id, cf, nome, cognome, data_nascita, residenza, grado_dolore, sintomi, data_ricovero,
data_dimissione, reparto, n_stanza, n_letto)
dett = dettagli_paziente_ricoverato()
return render_template('dettagli_paziente_ricoverato.html', det_paz=dett)
def modifica_paziente(id,cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi,data_ricovero,data_dimissione,reparto,n_stanza,n_letto):
connection1 = pymssql.connect(database="UNICLINIC")
connection2 = pymssql.connect(database="UNICLINIC")
cursor1 = connection1.cursor()
cursor2 = connection2.cursor()
cursor1.execute("UPDATE paziente SET CF = (%s), nome = (%s), cognome = (&s), \
data_di_nascita = (%s), residenza = (%s), grado_dolore = (%d), sintomi = (%s) WHERE ID_paziente = %d",(cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi, int(id) ))
cursor2.execute("UPDATE ricoverato SET data_ricovero = (6s), \
data_dimissione = (%s), COD_reparto = (%s), n_stanza = (%s), n_letto = (%s) \
WHERE ID_paziente = (%d)"
,(data_ricovero, data_dimissione, reparto, n_stanza, n_letto,int(id)))
connection1.commit()
connection2.commit()
cursor1.close()
cursor2.close()
connection1.close()
connection2.close()
def dett_id_paz():
id = request.form['id_paziente']
print(id)
return id
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modifica paziente | UNICLINIC</title>
<link rel="stylesheet" href={{ url_for('static', filename='style.css') }} type="text/css" media="all"/>
</head>
<body>
<div>
<table class="head_banner">
<tr>
<td><img id="logo" src={{ url_for('static', filename='immagini/logo_uniclinic.png') }} alt="Logo UNICLINIC"/></td>
<td class="menu"><button class="menu_btn">HOME</button></td>
<td class="menu"><button class="menu_btn">LOGIN</button></td>
<td class="menu"><button class="menu_btn">CONTACTS</button></td>
</tr>
</table>
<table class="tab_hd">
<thead>
<th>
<td colspan="2" id="p_tit">Dati profilo di {{det_paz.nome}} {{det_paz.cognome}}<td>
</th>
</thead>
</table>
<table class="tab_profilo">
<form id="modifica" method="post" action="salva_modifiche_paziente" class="form">
<tr>
<td class="p_dn">ID paziente:</td>
<td class="p_dv">
{{det_paz.id}}
<input style="display:none" id="id_paziente" name="id_paziente" type="text" value="{{det_paz.id}}" />
</td>
</tr>
<tr>
<td class="p_dn">Codice Fiscale:</td>
<td class="p_dv">
<input type="text" id="cf" name="cf " value="{{det_paz.cf}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Nome:</td>
<td class="p_dv">
<input type="text" id="nome" name="nome" value="{{det_paz.nome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Cognome:</td>
<td class="p_dv">
<input type="text" id="cognome" name="cognome" value="{{det_paz.cognome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data di nascita:</td>
<td class="p_dv">
<input type="date" id="data_nascita" name="data_nascita" value="{{det_paz.data_nascita}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Residenza:</td>
<td class="p_dv">
<input type="text" id="residenza" name="residenza" value="{{det_paz.residenza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Grado dolore:</td>
<td class="p_dv">
<select name="grado_dolore" id="grd_d">
{% for g in range(10) %}
<option type="text" id="grado_dolore" name="grado_dolore" value="{{g+1}}">Grado {{g+1}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Sintomi:</td>
<td class="p_dv">
<input type="text" id="sintmi" name="sintomi" value="{{det_paz.sintomi}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data ricovero:</td>
<td class="p_dv">
<input type="date" id="data_ricovero" name="data_ricovero" value="{{det_paz.data_ricovero}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data dimissione:</td>
<td class="p_dv">
<input type="date" id="data_dimissione" name="data_dimissione" value="{{det_paz.data_dimissione}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Reparto ricovero:</td>
<td class="p_dv">
<label for="reparto"></label>
<select name="reparto" id="rep" class="p_dv">
{% for reparto in rep %}
<option type="text" id="reparto" name="reparto" value="{{reparto.COD_reparto}}">{{reparto.COD_reparto}} - {{reparto.nome_reparto}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Stanza nr.:</td>
<td class="p_dv">
<input type="text" id="n_stanza" name="n_stanza" value="{{det_paz.n_stanza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Letto nr.:</td>
<td class="p_dv">
<input type="text" id="n_letto" name="n_letto" value="{{det_paz.n_letto}}"/>
</td>
</tr>
<tr class="r_bd">
<td class="b_dn"><button type="submit" form="modifica" class="menu_btn_d">CONFERMA</button></td>
<td class="b_dn"><button type="reset" class="menu_btn_d">ANNULLA</button></td>
</tr>
</form>
</table>
</div>
</body>
</html>
I'm using Flask and Jinja2 and I need to make an attendance table that includes both editable and non-editable fields. I referred to other posts such as here and here which got me to this point. The table successfully displays the editable fields using FieldList. However, I have not been able to render the non-editable fields.
This is what the table should look like:
The only fields which should be editable are "attendance code" and "comment". Unfortunately, I have not found a way to include the other fields (class name, start time, end time, first name, last name) as simple text fields.
I have tried using the read-only attribute for WTForms. While this is functional, it displays the text in text boxes which don't look appealing.
My latest attempt shown below defines a WTForms class called updateStudentAttendanceForm that inherits the fields from another class called attendanceLogClass that includes instance variables for the desired fields. I assign the values to the form class in the routes.py file. However, when I reference these variables in the html file, they result in blank fields. I have used a print statement to verify the variable assignments are working properly. I cannot figure out why the variables do not display properly when included in the html template.
forms.py
class attendanceLogClass:
def __init__(self):
self.classAttendanceLogId = int()
self.className = str()
self.firstName = str()
self.lastName = str()
self.startTime = datetime()
self.endTime = datetime()
def __repr__(self):
return f"attendanceLogClass('{self.classAttendanceLogId}','{self.className}','{self.firstName}','{self.lastName}','{self.startTime}','{self.endTime}')"
class updateStudentAttendanceForm(FlaskForm, attendanceLogClass):
attendanceCode = RadioField(
"Attendance Code",
choices=[("P", "P"), ("T", "T"), ("E", "E"), ("U", "U"), ("Q", "?"),],
)
comment = StringField("Comment")
submit = SubmitField("Submit Attendance")
class updateClassAttendanceForm(FlaskForm):
title = StringField("title")
classMembers = FieldList(FormField(updateStudentAttendanceForm))
routes.py
#app.route("/classattendancelog")
def displayClassAttendanceLog():
classAttendanceForm = updateClassAttendanceForm()
classAttendanceForm.title.data = "My class"
for studentAttendance in ClassAttendanceLog.query.all():
studentAttendanceForm = updateStudentAttendanceForm()
studentAttendanceForm.className = studentAttendance.ClassSchedule.className
studentAttendanceForm.classAttendanceLogId = studentAttendance.id
studentAttendanceForm.className = studentAttendance.ClassSchedule.className
studentAttendanceForm.startTime = studentAttendance.ClassSchedule.startTime
studentAttendanceForm.endTime = studentAttendance.ClassSchedule.endTime
studentAttendanceForm.firstName = (
studentAttendance.ClassSchedule.Student.firstName
)
studentAttendanceForm.lastName = (
studentAttendance.ClassSchedule.Student.lastName
)
studentAttendanceForm.attendanceCode = studentAttendance.attendanceCode
studentAttendanceForm.comment = studentAttendance.comment
# The following print statement verified that all of the variables are properly defined based on the values retrieved from the database query
print(studentAttendanceForm)
classAttendanceForm.classMembers.append_entry(studentAttendanceForm)
return render_template(
"classattendancelog.html",
title="Class Attendance Log",
classAttendanceForm=classAttendanceForm,
)
classattendancelog.html:
{% extends 'layout.html'%}
{% block content %}
<h1> Class Attendance </h1>
<form method="POST" action="" enctype="multipart/form-data">
{{ classAttendanceForm.hidden_tag() }}
<table class="table table-sm table-hover">
<thead class="thead-light">
<tr>
<th scope="col">Class Name</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Attendance Code</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
{% for studentAttendanceForm in classAttendanceForm.classMembers %}
<tr>
<td> {{ studentAttendanceForm.className }}</td>
<td> {{ studentAttendanceForm.startTime }}</td>
<td> {{ studentAttendanceForm.endTime }}</td>
<td> {{ studentAttendanceForm.firstName }}</td>
<td> {{ studentAttendanceForm.lastName }} </td>
<td>
{% for subfield in studentAttendanceForm.attendanceCode %}
{{ subfield }}
{{ subfield.label }}
{% endfor %}
</td>
<td>
{{ studentAttendanceForm.comment(class="form-control form-control-sm") }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
Note: I haven't yet written the code to handle the form response.
I solved the problem by using the zip function to iterate simultaneously through two lists: one list with the FormField data and a second list with the non-editable "fixed field" data.
To use "zip" in the HTML template, I followed the instructions here and added this line to my init.py
app.jinja_env.globals.update(zip=zip)
updated forms.py (eliminated attendanceLogClass with fixed field variables):
class updateStudentAttendanceForm(FlaskForm):
attendanceCode = RadioField(
"Attendance Code",
choices=[("P", "P"), ("T", "T"), ("E", "E"), ("U", "U"), ("Q", "?"),],
)
comment = StringField("Comment")
submit = SubmitField("Submit Attendance")
class updateClassAttendanceForm(FlaskForm):
title = StringField("title")
classMembers = FieldList(FormField(updateStudentAttendanceForm))
updated routes.py (added new variable for fixed fields called classAttendanceFixedFields):
#app.route("/classattendancelog")
def displayClassAttendanceLog():
classAttendanceFixedFields = ClassAttendanceLog.query.all()
classAttendanceForm = updateClassAttendanceForm()
classAttendanceForm.title.data = "My class"
for studentAttendance in ClassAttendanceLog.query.all():
studentAttendanceForm = updateStudentAttendanceForm()
studentAttendanceForm.attendanceCode = studentAttendance.attendanceCode
studentAttendanceForm.comment = studentAttendance.comment
classAttendanceForm.classMembers.append_entry(studentAttendanceForm)
return render_template(
"classattendancelog.html",
title="Class Attendance Log",
classAttendanceForm=classAttendanceForm,
classAttendanceFixedFields=classAttendanceFixedFields,
)
updated classattendancelog.html (incorporated zip function in the for loop to simultaneously iterate through the editable fields and fixed fields).
{% extends 'layout.html'%}
{% block content %}
<h1> Class Attendance </h1>
<form method="POST" action="" enctype="multipart/form-data">
{{ classAttendanceForm.hidden_tag() }}
<table class="table table-sm table-hover">
<thead class="thead-light">
<tr>
<th scope="col">Class Name</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Attendance Code</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
{% for studentAttendanceForm, studentFixedFields in zip(classAttendanceForm.classMembers, classAttendanceFixedFields) %}
<tr>
<td> {{ studentFixedFields.ClassSchedule.className }}</td>
<td> {{ studentFixedFields.ClassSchedule.startTime.strftime('%-I:%M') }}</td>
<td> {{ studentFixedFields.ClassSchedule.endTime.strftime('%-I:%M') }}</td>
<td> {{ studentFixedFields.ClassSchedule.Student.firstName }}</td>
<td> {{ studentFixedFields.ClassSchedule.Student.lastName }} </td>
<td>
{% for subfield in studentAttendanceForm.attendanceCode %}
{{ subfield }}
{{ subfield.label }}
{% endfor %}
</td>
<td>
{{ studentAttendanceForm.comment(class="form-control form-control-sm") }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
I want to compare a 'term' to the values of a dictionary, specifically, the substrings of the values. This is necessary because the formatting of the values varies across different modules. For instance: module1='Doe', module2='Jane Doe'. The term to compare in this case would be 'Doe'. How should I go about solving this issue? Thanks!
search.html
{% if tickets %}
Tickets found:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Company</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
{% for ticket in tickets %}
<tr>
<td> {{ ticket.id }} </td>
<td> {{ ticket.company.name }} </td>
<td> {{ ticket.summary }} </td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
views.py
def search_bar(request):
term = request.GET.get('term')
if term:
results = objCW.search_companies(term) + objCW.search_contacts(term)
tickets = objCW.search_tickets_by_company(term) + objCW.search_tickets_by_contact(term)
context = {'results': results, 'tickets': tickets}
return render(request, 'website/search.html', context)
else:
context = {'': ''}
return render(request, 'website/search.html', context)
I have 2 classes and I´d like to show a list of fields from the second class based on the first class. For example:
servico:
id desc_servico
1 teste1
2 teste2
itemservico:
id desc_itemservico servico
1 itemteste1 1
2 itemteste2 2
In this example, if I choose servico=1, the itemservico has to show me itemteste1. If I choose servico=2, the itemservico has to show itemteste2.
Models.py:
class servico(models.Model):
desc_servico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False)
class itemservico(models.Model):
desc_itemservico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False)
val_itemservico = models.DecimalField(max_digits=8, decimal_places=2)
servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Serviço
ind_selecionado = models.BooleanField(default=False)
forms.py:
class itemservicoForm(forms.ModelForm):
servico = forms.ModelChoiceField(queryset=servico.objects.all().order_by('desc_servico'), empty_label="Serviço")
class Meta:
model = itemservico
fields = (
'servico',
)
template.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ORÇAMENTO</title>
</head>
<body>
<h2>ORÇAMENTO</h2>
<form class=" bd-form-20 " action="" name="form-name" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label class="bd-form-label" >Serviço </label>{{form.servico}}<br><br>
<p><h1>{{form.servivo.id}}</h1></p>
<div class=" bd-customhtml-29 bd-tagstyles bd-custom-table">
<div class="bd-container-inner bd-content-element">
<table border="1" rules="all" cellspacing="0" cellpadding="10">
<tbody>
<tr>
<th>Testar</th>
<th>Selecionar</th>
<th>ID Item Serviço</th>
<th>Item Serviço</th>
<th>Valor Serviço</th>
<th>Serviço</th>
</tr>
{% for item in instance_itens %}
<tr>
<td> <input type="checkbox" id="item.ind_selecionado"></td>
<td>{{ item.ind_selecionado }}</td>
<td>{{ item.id }}</td>
<td>{{ item.desc_itemservico }}</td>
<td>{{ item.val_itemservico }}</td>
<td>{{ item.servico_id}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</form>
<br><br>
<button class="bd-linkbutton-60 bd-button bd-own-margins bd-content-element" type = "submit" >
OK</button>
</body>
</html>
I think you need to use Ajax post for generating results based on selection.
for view.py part you need use this function:
def ajax_post(request):
if request.POST:
if request.POST.get('servico') and request.is_ajax():
itemservico_list = itemservico.objects.filter(servico = request.POST.get('servico'))
return render_to_response('itemservico.html',{'itemservico_list':itemservico_list})
For Html part you need to generate itemservico.html seperated and include it to main html such as
<form method="post">{% csrf_token %}
<tbody><tr>
<th>Testar</th>
<th>Selecionar</th>
<th>ID Item Serviço</th>
<th>Item Serviço</th>
<th>Valor Serviço</th>
<th id='targetselection'>Serviço</th>
</tr>
<div id='inner'>
{% include "itemservico.html" %}
</div>
</tbody>
</form>
And you need to create another html file for itemservico such as
{% for item in itemservico_list %}
<tr>
<td> <input type="checkbox" id="item.ind_selecionado"></td>
<td>{{ item.ind_selecionado }}</td>
<td>{{ item.id }}</td>
<td>{{ item.desc_itemservico }}</td>
<td>{{ item.val_itemservico }}</td>
<td>{{ item.servico_id}}</td>
</tr>
{% endfor %}
For JS part you need to create a js file for which detect state changes or key press of any given field: (I use jquery for selection)
$('#targetselection').on('change keyup paste', function() {
servico = $(this).val() // get the current value of the input field.
ajaxPost(servico);
});
function ajaxPost(query){
$.ajax({
type:"POST",
url:'',
data: {
csrfmiddlewaretoken:token,
servico : servico
},
dataType:'html',
success:function (data,textStatus,jqXHR){
$('#inner').html(data);
}
});
}
As a summary: When some selection changes on the web site, its creating an ajax request on server. As a view part you are filtering data according to ajax post request. Rendering html file and pushing it into specific part of web page. I hope this would be helpfull