How can I get the Field Names to return as text/string?
Highlighted "Field Names" I want returned as text, not fields
I am dynamically creating a list of fields and then appending values. But I can't seem to figure out a way to return the field names as plain text. The below code appends them to a field (fieldname)-- which is the only way I have been able to return them.
class ContractFields(FlaskForm):
fieldname = StringField()
fieldvalue = StringField()
class ContractForm(FlaskForm):
title = StringField('title')
contractfieldlist = FieldList(FormField(ContractFields))
#app.route('/tester.html', methods=['GET','POST'])
def contractfields():
form = ContractForm()
for f in object:
document_form = ContractFields()
document_form.fieldname = f.name #need this list object to return as table text, not a field
document_form.fieldvalue = f.value
form.contractfieldlist.append_entry(document_form)
return render_template('tester.html', form = form)
And from the template:
<div>
<form action="" method="post" name="form">
{{ form.hidden_tag() }}
<div>
<table>
<tr>
<th> ListNumber </th>
<th> Field Name </th>
<th> Field Value </th>
</tr>
{% for items in form.contractfieldlist %}
<tr>
<td>{{ items.label }}</td>
<td>{{ items.fieldname }}</td>
<td>{{ items.fieldvalue }}</td>
</tr>
{% endfor %}
</table>
</div>
<p><input type="submit" name="edit" value="Send"></p>
</form>
</div>
My experience with Python has largely been limited ETL and data transformation so I don't understand why this was so complicated. But after way too many hours I finally found the following solution worked for me.
Specifically modifying the associated excerpt from the above post to be the following:
class ContractFields(FlaskForm):
fieldname = HiddenField()
fieldvalue = StringField()
def __init__(self, *args, **kwargs):
super(ContractFields, self).__init__(*args, **kwargs)
if 'obj' in kwargs and kwargs['obj'] is not None:
self.fieldvalue.label.text = kwargs['obj'].fieldname
And the template html to:
<td>{{ items.label }}</td>
<td>{{ items.fieldvalue.label }}</td>
<td>{{ items.fieldvalue }}</td>
Related
I wanted to get multiple id's from a list using checkbox. I got an error
Field 'id' expected a number but got [].
Below is my code.
sample.html
<button href="/sample/save">Save</button>
{% for obj in queryset %}
<tr>
<td><input type="checkbox" name="sid" value="{{obj.id}}"></td>
<td>{{ obj.sample_name }}</td>
<td>{{ obj.sample_type}}</td>
<td>{{ obj.number}}</td>
</tr>
{% endfor %}
views.py
def sample(request):
if request.method == 'GET':
queryset = SampleList.objects.all()
return render(request, 'lab_management/sample.html', {'queryset': queryset})
def save_doc(request):
sid = request.POST.getlist('sid')
sample = SampleList.objects.filter(id=sid)[0:10]
template = DocxTemplate("doc.docx")
context = {
'headers' : ['Name', 'Type', 'Number'],
'doc': [],
}
for samp in sample:
list = [samp.name, samp.type, samp.number]
context['doc'].append(list)
template.render(context)
template.save('new_doc.docx')
the field id should be int you passed a list, that's why you got error:
Field 'id' expected a number but got [].
Here you can use the in Filed lookup
Try this
sample = SampleList.objects.filter(id__in=sid)[0:10]
this will show all the SampleList items with the id's in sid
Update
Change your context to
context = {
'headers' : ['Name', 'Type', 'Number'],
'doc': sample,
}
then remove this for loop
# for samp in sample:
# list = [samp.name, samp.type, samp.number]
# context['doc'].append(list)
and in your template
{% for obj in doc %}
<tr>
<td><input type="checkbox" name="sid" value="{{obj.id}}"></td>
<td>{{ obj.name }}</td>
<td>{{ obj.type}}</td>
<td>{{ obj.number}}</td>
</tr>
{% endfor %}
NB: assuming name, type and number are the filed names of SampleList model
Does anybody knows how can I use count based on selected value using django_filters
Error
'UserFilter' object has no attribute 'count'
My Reference link
views.py
def search(request):
user_list = Person.objects.all()
user_filter = UserFilter(request.GET, queryset=user_list)
count = user_filter.count() #this will return an error
print(count)
return render(request, 'user_list.html', {'filter': user_filter})
filters.py
from django.contrib.auth.models import User
from .models import Person
import django_filters
class UserFilter(django_filters.FilterSet):
class Meta:
model = Person
fields = ['category', 'firstname', 'lastname' ]
user_list.html
{% extends 'base.html' %}
{% block content %}
<form method="get">
{{filter.form.as_p}}
<button type="submit" >Search</button>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th>Firstname</th>
<th> Lastname</th>
<th>Caegory</th>
</tr>
</thead>
<tbody>
{% for user in filter.qs %}
<tr>
<td>{{ user.firstname }}</td>
<td>{{ user.lastname }}</td>
<td>{{ user.category }}</td>
</tr>
{% empty %}
<tr>
<td colspan="5">No data</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
I want to count all the list base from data I filtered
You'll want the count of the resulting queryset, which you can get from the filter's qs property (as you do in your template!).
Change
count = user_filter.count()
to
count = user_filter.qs.count()
You can work with the .qs attribute:
def search(request):
user_list = Person.objects.all()
user_filter = UserFilter(request.GET, queryset=user_list)
count = user_filter.qs.count()
return render(request, 'user_list.html', {'filter': user_filter})
.qs [GitHub] is a property that generates a QuerySet by filtering the original queryset by values in the fields of the FilterSet.
My Django View:
def hub(request):
context = {}
hub_id = [value['id'] for value in hub_data['data']]
hub_name = [value['attributes']['name'] for value in hub_data['data']]
hub_url = [value['links']['self']['href'] for value in hub_data['data']]
nested_dict = dict(zip(hub_name, map(list, zip(hub_id, hub_url))))
context ['rows'] = nested_dict
return render(request, 'connector/hub.html', context)
The context['rows'] results in:
{'rows': {hub_name1 : ['hub_id1', 'hub_url1'],{hub_name2 : ['hub_id2', 'hub_url2'], etc.. }
I am trying to pass it a HTML table that looks like this:
<th scope="col">Hub Name</th>
<th scope="col">Hub ID</th>
<th scope="col">Hub URL</th>
My tablebody looks like this:
<tbody>
{% for key, value in rows.items %}
<tr>
<td> {{ key }}</td>
<td> {{ value }}</td> **//how do i just get hub_id here**
<td> Don't know what to do here to get: hub_url </td>
</tr>
{% endfor %}
</tbody>
But I want to add another -tag to fill with hub_url. How do I extract the hub_id data and add it to the column: Hub ID and extract the hub_url and add it to the column Hub URL.
Any help would be much appreciated!
You can pass the data to the template without transforming it
return render(request, 'connector/hub.html', {'data': hub_data['data']})
And then lookup the attributes using the "dot" template syntax for each row
<tbody>
{% for row in data %}
<tr>
<td>{{ row.attributes.name }}</td>
<td>{{ row.id }}</td>
<td>{{ row.links.self.href }}</td>
</tr>
{% endfor %}
</tbody>
I have a Django table with 3 fields.
I have a total of 4 entries and i want to visualize all of them inside a table which only displays 2 of these 3 fields.
How should i do that? i did manage to only display 1 row instead of 4, i'm struggling, someone could help?
This is the easy model to manage.
class Inc(models.Model):
id = models.AutoField(primary_key=True)
nr_sin = models.CharField(max_length=50, default=None)
nr_pol = models.CharField(max_length=50, default=None)
Have you already got the QuerySet being passed from your view to your templates?
Assuming you have, and it's in a variable called inc_list, then in your template you could do this to display the nr_sin and nr_pol fields:
{% if inc_list %}
<table>
<thead>
<tr>
<th>NR SIN</th>
<th>NR POL</th>
</tr>
</thead>
<tbody>
{% for inc in inc_list %}
<tr>
<td>{{ inc.nr_sin }}</td>
<td>{{ inc.nr_pol }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
In you view query your model to get all the entries you want to display in the table and pass them as a context variable to the templete. Later in the template you have to iterate over the list of elements and render one by one as follow:
# import your model
class SomeView(View):
def get(self, request):
elements = Inc.objects.all()
context = {'elements': elements}
return render(request, 'your_template.html', context)
render the table:
<table>
<thead>
<tr>
<th>ID</th>
<th>nr_sin</th>
</tr>
</thead>
<tbody>
{# you loop over the list and render one element at each iteration #}
{% for inc in elements %}
<tr>
<td>{{ inc.pk }}</td>
<td>{{ inc.nr_sin }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I'm struggling to see how this is done, and the documentation doesn't seem to help much.
I need to generate a table, the row size will be variable, but not dynamic (i know how much rows i need before generating the page).
For the sake of simplicity lets imagine a page where you grade n exams with an integer.
i tried this:
the form.
class InputInteger(Form):
grade = IntegerField('Grade')
the view
#decorator..
def grade():
form = InputInteger()
names = student_list
return render_template("grade.html", form=form, names=names)
the template
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>
{{name}}
</td>
<td>
{{form.grade}}
</td>
</tr>
</table>
But how do i read back the inputed values?
How do i distinguish who's grade that belongs too?
Am fairly confused, i've read about FieldList(FormField(IntegerField)), but isn't that just one field with a list of integers?
What about the Table Widget, do i need that?
Please help.
For anyone looking at this now, the OP was correct to think about FieldLists and FormFields. Here is a solution:
forms.py:
class GradeForm(FlaskForm):
student = IntegerField('Student ID')
grade = IntegerField('Grade')
delete = BooleanField('Delete')
class GradeFormSet(FlaskForm):
gradeset = FieldList(FormField(GradeForm), min_entries=0)
view.py:
def grade():
# create a dict of student IDs and their initial grades (or None for now)
init_merits = [dict(student=s.id, grade=None) for s in myStudentTable.query.all()]
gradeform = GradeFormSet(gradeset=init_merits)
if form.validate_on_submit():
...
# meritforms.data['gradeset'] contains a list of dictionary values for further processing
# check 'delete' == True to handle deletion of that student from your table
...
return render_template('template.html', form=gradeform)
Template:
<table>
{% for merit in form.gradeset %}
<tr>
<td>{{ merit.placing(readonly=true) }} {{ merit.csrf_token }} {{ merit.hidden_tag() }}</td>
<td>{{ merit.grade }}</td>
<td>{{ merit.delete }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" name="finish" value="Save">
<input type="submit" name="cancel" value="Cancel">
You're almost right. Put your table inside a html form and catch in a function where you can retrieve your input fields.
Here is an example:
<form action="/grade">
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>{{name}}</td>
<td><input id='{{name}}' value='{{ form.grade }}'></td>
</tr>
</table>
</form>
And your Flask function:
#app.route('/grade', methods=['GET', 'POST'])
def grade():
if request.method == 'POST':
return 'Form posted.'
When you post your form to your function, you can access your input field by this way: request.form['inputfieldname'] and then you do your stuff. I hope my explanation is clear.