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)})
Related
I am trying to create a search page where buttons can be clicked which will filter the posts like in this page [Splice Sounds][2] (i think you need an account to view this so ill add screenshots).
To do this i think i need to pass a list so that i can filter by that list but i can't find a way to do this.
having a GET form for each genre (which is being created by a for loop) would allow me to filter by one genre at a time but i want to filter by multple genres at once so that won't work
in the site that i linked to: they pass the genres/tags into the url so how could i do this in django?
Also: i could make seperate url paths and link to those but then i would have to do this for every combination of genres/tags which would be too much so i can't do that.
the link shows a site which passes tags through url like this https://splice.com/sounds/search?sound_type=sample&tag=drums,kicks
here is some relevant code:
this is how i want to filter which is why i need to pass a list of args
for arg in args:
Posts = Posts.filter(genres=arg)
urls
urlpatterns = [
path('', views.find, name='find'),
path('searchgenres=<genres_selected>', views.find_search, name='find_search'),
]
EDIT: I have tried this many ways such as using ajax but i couldn't get that to work well
EDIT 2: i have changed the question to How To Pass Only Selected Arguments Through URL
To pass a list into a request you could:
Use html checkboxes and in views aggregate them into a list
Use a single textbox and parse in views
If you obtain the request as a list, you could use Post.objects.filter(genre__in=genres).
It might also be helpful to know that Django allows for complex lookups with Q objects from django.db.models import Q. The | character represents OR. This allows complex filtering. For instance:
Posts.objects.filter(Q(genre='Pop') | Q(genre='Rock') | Q(genre='Jazz'))
After extensive googling, I still havent come up with an effecient way to solve this.
Im creating a website using Django. I have a db which contains time data, more specifically dates. The value for "the present" is set to 3000-01-01 (YYYY-MM-DD) as is common practice for time-querying.
What I want to do is display a string like "Now" or "Present" or any other value instead of the date 3000-01-01. Is there some sort of global override anywhere that I can use? Seems like a waste to hard-code it in every view/template.
Cheers!
Since this is rendering, I would advice against "subclassing" the DateField such that it renders 'now' instead of the original date(..) object: it will make calculations in the model layer more cumbersome.
Probably a good way to deal with this is implementing a template filter [Django-doc], for example we can construct a file:
# app/templatetags/nowdate.py
from django import template
register = template.Library()
PRESENT = date(3000, 1, 1)
#register.filter
def nowdate(value):
if value == PRESENT:
return 'present'
return value
The templatetags directory of the app application, needs to contain an __init__.py file as well (an empty file), and the app of course needs to be part of the INSTALLED_APPS in the settings.py.
Then we can use it in the template like:
<!-- app/templates/app/some_template.html -->
{{ some_model.some_date_field|nowdate }}
Here we thus fetch the some_date_field of the some_model variable (this attribute is thus a date(..) object), and we pass it through the nowdate filter we have constructed such that, if it is 3000-01-01, it is replaced by the 'present' string.
The advantage here is that if we later change our mind about what date the "present" is, we can easily change it in the template filter, furthermore we can easily extend it, for example by adding a 'past', 'future', etc.
i able to print values from below code in django views
subMarks = []
for item in marks:
for column in gridHeaderTableData:
subMark = item[column['sub_exam_name']]
subMarks.append(subMark)
how to write above code in django templates
You can't set any variables in templates, it's actually not Python language. What is you can do, just write this code into your view, save result as variable, and push to your template, where you can print what you want.
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.
I have a few checkboxes with common name and individual variables (ID).
How can I in python read them as list?
Now I'm using
checkbox= request.POST["common_name"]
It isn't work properly, checkbox variable store only the last checked box instead of any list or something.
If you were using WebOB, request.POST.getall('common_name') would give you a list of all the POST variables with the name 'common_name'. See the WebOB docs for more.
But you aren't - you're using Django. See the QueryDict docs for several ways to do this - request.POST.getlist('common_name') is one way to do it.
checkbox = request.POST.getlist("common_name")
And if you want to select objects (say Contact objects) based upon the getlist list, you can do this:
selected_ids = request.POST.getlist('_selected_for_action')
object_list = Contact.objects.filter(pk__in=selected_ids)