Generating random ID from list - jinja - python

I am trying to generate a random ID from a list of contacts (in Python, with jinja2) to display in an HTML template.
So I have a list of contacts, and for the moment I display all of them in a few cells in my HTML template by looping through the list of contacts:
# for contact_db in contact_dbs
<tr>
<td>{{contact_db.key.id()}}</td>
<td>{{contact_db.name}}</td>
<td>{{contact_db.phone}}</td>
<td>{{contact_db.email}}</td>
</tr>
# endfor
The view that renders the above is:
def contact_list():
contact_dbs, contact_cursor = model.Contact.get_dbs(
user_key=auth.current_user_key(),
)
return flask.render_template(
'contact_list.html',
html_class='contact-list',
title='Contacts',
contact_dbs=contact_dbs,
next_url=util.generate_next_url(contact_cursor),
)
Instead, I would like to display one contact, selected randomly by its ID, and it should display another contact with all its information every time the user refreshes the page (I am not dealing with displaying the same contact twice for now by the way).
I know that it is possible to use random in a python file to deal with random choices, so but not sure how it translates in jinja in the template.
Any help appreciated thanks!

There is a random filter in jinja2.
random(seq)
Return a random item from the sequence.
Use it like this:
{% set selected_contact = contact_dbs|random %}
note: I assumed contact_dbs is iterable.

Related

Django Randomly Select List Item to Display In Template

I have a list of strings in a .py file located in the same dir as my working app. I want to display a randomly selected item from the list and have it display in the template of my app. On each refresh of the page i want the random selection to change. I can't work out how this is possible at the moment.
I'm thinking two things: run a random selection within the .py that has my list; or bring the entire list into the template and then use JS(?) to randomly select an item.
Any advice?
Django has a template filter for that: random. You can use it on lists, e.g.:
{{ list_of_values|random }}
If you ever want to be able to cache the page though, you might want to consider a JavaScript-based solution like you mentioned.
Use the choices function from the random module.
views.py
import random
from somewhere.filename import strings
def index(request):
return render('template.html', {'list_item', random.choice(strings)})

How can I edit data fetched from db in html table ? Flask, Jinja2

I'm afraid the title isn't so clear as I want it to be, but I'll try to explain more detailed:
I had a db's table :
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
task = db.Column(db.String(10),index=True)
descr = db.Column(db.String(300),index=True,unique=True)
docs = db.relationship('Doc', backref='Task', lazy='dynamic'
this query docs = Task.query.all()
and some html page with a loop:
<table>
{% for doc in docs %}
<tr><td>{{doc.id}}</td><td>{{doc.task}}</td><td>{{doc.descr}}</td><td>
{% endfor %}
</table>
this all works well and looks like usual html table filled with data from my db (sqlite). Like this, but it's just another table, no matter.
Sometimes the data have missing values like the last column in this pic, it's normal because I want to fill that later. How can I implement such functionality ? I've tried many things.. The problem is that i don't know how to get another info from currently edited row to make correct record to database.
For example, lets's take the second row and add some data to last column -> submit. Now i must somehow get from this row '234' or 'sfdfs' to make
edit_ task = Task.query.filter_by(task=234).first() or
Task.query.filter_by(descr=sfdfs).first()
get the result of this query and simply add new info to unfilled column and than commit.
I can make different forms, requests and other things, but I just don't understand how to make this function in propper way? Shoul i use JS to get info from table in the template, than transfer it to form and than to python /route function? or there is another decision ? may be this html table must be some kind of WTFotms table.widget form? Any ideas would be greatly appreciated. Thx
http://www.blog.pythonlibrary.org/2017/12/14/flask-101-adding-editing-and-displaying-data/ the only way i managed to find. Just don't create an html-table mannualy with cycling , Table Class from flask_table can make it for you and there is also an oppurtunity to make edit link.
Just found this blog post about Grid.js. It makes it possible to edit table cells directly on a page without extra Edit links.

Dynamic HTML content and Python variables with Flask

On the user end, say I have people selecting school records through a form to display in a table below.
For instance, they choose their name from a list of names, and that pulls their records from a database.
Dependent on their class year, they may have 1, 2, 3, or 4 years of records, so the data pulled will always look different.
After they submit the form, their records are stored in a variable containing all their records, and then each record is broken down into subtypes, for instance, all records in the English department. Those subtypes are stored in other lists--so there's a list for all English records. Let's call that variable english_records. I want to use these subtype variables to be able to present only the data users want to see, and to present all data in that particular list.
So using Flask's render_template function, I'm trying to send each of these records to an html template that will create a table cell for each record.
What I've been trying (that hasn't worked so far) is something like:
Python:
i = 0
def index():
for e in english_records:
english_records = [
{
'english': english_records[i]
}
]
i = i + 1
return render_template("index.html",
english_records = english_records)
And in HTML:
...table above...
{% for record in english_records %}
<td>
{{record.english}}
</td>
{% endfor %}
...table continues...
Thus far I've been getting table cells created for each record, but the records not being passed through. Anyone know how to do this?
Is there a reason why you're pre-processing the data? What does english_records look like? If my hunch is correct, then you shouldn't actually need the for loop at all.
There's also the issue that you're overwriting the initial english_records variable with english_records within the for loop, so the assignment, while legal in terms of syntax, is logically nonsensical.
Another issue is that, depending on the actual type of the first english_records, you shouldn't need to use a counter: if english_records is a list, then it'll contain the value you're looking for. If english_records is a dict, then enumerating it might look like for key, val in english_records.iteritems().
for e in english_records:
english_records = [
{
'english': english_records[i]
}
]
i = i + 1
This loop here is creating a list , but the members of those list do not have 'english' key ,
so in the template, the loop is executed, but there is no value for {{record.english}} , hence it is ignored.
All you will get is table rows without any data.

pyramid checkboxes

I'm just new to python and pyramid and I'm struggling with how to process the results of a form containing multiple checkboxes in Pyramid.
Here is an excerpt from my form:
<p tal:repeat="category categories">
<input type="checkbox" name="selectedcategories" value="${category.id}"> ${category.name}<br/>
</p>
And here is how I am currently trying to iterate through and process the results:
selectedcategories=request.params['selectedcategories']
for categoryid in selectedcategories:
category = DBSession.query(Category).filter_by(id=categoryid).one()
article.categories.append(category)
As you may have guessed, I'm only getting a maximum of one checkbox recognized no matter how many I select on the form. Django has an option to return the results as a list, but I can't seem to figure out how to do that with Pyramid.
request.params is a multidict. To retrieve multiple values, you can call its getall() method:
selectedcategories = request.params.getall("selectedcategories")

Python / Django - Form Selection Value is Object Id... Can't Get Object

I have a form select box that has values corresponding to objects. The user selects an input and the form submits. I then want to take that value and retrieve the object that has an ID equivalent to the selected form value. However, when I try to do so, I'm getting an error like so:
int() argument must be a string or a number, not 'Cars'
Example:
if form.is_valid():
car = Car.objects.get(id=form.cleaned_data['id'])
I'm guessing the problem is that the returned value is a string and NOT an integer. In PHP this is SIMPLE. How do I typecast or use the returned form value to get an associated object?
Seems as though Django is not returning the value of the form element, but instead the user visible option name...
Form Class:
class CarForm(forms.ModelForm):
class Meta:
model = Car
Html Form:
<form action="">
<select name="id">
{% for car in cars %}
<option value="{{car.id}}">{{car.title}}</option>
{% endfor %}
</select>
</form>
The id field has to be an integer, or a string that can be converted to an integer.
Simple as that!
Somehow, your form.cleaned_data['id'] is returning a model called Cars
Ensure it returns a number if you want to pass it into get(id=
You can use ModelChoiceField instead of generating the select using HTML
in forms.py:
class CarSelectForm(forms.Form):
car = forms.ModelChoiceField(queryset=Car.objects.all(), empty_label=None)
in view.py:
if form.is_valid():
car = form.cleaned_data['car']
This is maybe a bad, but I think working answer. If anyone has a real solution, please post because I still need it.
(I'm using a modelformset, but just a modelform may work the same)
For me, the {{ form.id }} works on the page (puts the id) and comes back correctly in the POST data. However, somewhere along the line it gets converted (as Yuji said in his post) into the model object represented by that id and that is what is in cleaned_data.
In short, change
car = Car.objects.get(id=form.cleaned_data['id'])
to
car = form.cleaned_data['id']
I think it just looks like a string just because when you print or debug, it's using your str or unicode representation.
Repeat: This is almost certainly a side effect or bad way to do things. If I figure out a better way, I'll post it.
I have the same issue... so I tried the following:
ts_1 = form.cleaned_data['lista_trabajos']
ts_2 = request.POST['lista_trabajos']
print(ts_1) # this returns what user sees, ex: 1 - folders
print(ts_2) # this returns value from that option, in my case: 1
Unfortunately, I have been reading that by using raw POST data is not recommended. At the moment, I cannot figure out how to validate and get the raw POST data by using something similar to "clean_data".
You can read about this in: https://books.google.com.ar/books?id=8sU7DwAAQBAJ&pg=PA229&lpg=PA229&dq=form+cleaned_data+to+get+raw+post+data&source=bl&ots=RN9WKRaGJs&sig=QpSoPdI9YSHSNk0zAQIO8phSbOw&hl=es&sa=X&ved=0ahUKEwiBouHattnaAhULFZAKHUKmA4QQ6AEIRzAD#v=onepage&q=form%20cleaned_data%20to%20get%20raw%20post%20data&f=false

Categories

Resources