How to access a given list element in django templates? - python

I have a list of values in my view where I want to store some classes name and pass them to the template. Here is the list in the view: menu = ['','disabled','','',''] and my code for the template <li class="{{ menu|slice:"1:2"|first }}"></li>.
So far this is the only working code I came with, is there a better way to retrieve the element menu[2] from this list? what is the proper way in django to callback the element[n] of a list within the template?

menu.1 should work
if you know the exact index of your list, it could be cleaner and more explicit to do retrieval in your view.
context['menu_target'] = menu[1]
instead of having a list of empty values and accessing them in your template

You can just use menu.2 in your template.

An alternative is to get the element[n] that you need in your view, and pass it to the template directly.
Generally speaking, It's a better approch to pass to the template the data that you're going to actually use. So why pass a full list to use only one item of it?

Related

How to get all elements by tag?

I use diskcache to persist my data. I save users cache.add(key=k, value=v, tag="users"), now i want to get all users by tag, but there is no such method.
How i can do this?
I've found only one way to do this:
def _get_all(self):
r = []
for k in list(self._cache.iterkeys()):
r.append(self._cache.get(key=k))
But this way does not assume tag as argument, so i can not persist in 1 diskcache instance different items and filter them by tag.
Looking at the source code of python-diskcache, the sole purpose of the tag is be used in an SQLite index which is meant to enable fast cache eviction/culling on the basis of a tag value.
The only SQL statement that tag is ever used in is in the .evict() method.
There is no official API to get cache entries by tag, and the library is not designed to do that. The whole underlying setup of the database and the item-retrieval mechanics are key-centered.

How to access to dictionary value via variables in another list in Django

I have this situation in my views.py
d = {'05:45':3,'06:30':6 (...) }
T = ['05:45','06:30' (...)]
I would like to get d[T[i]] in my HTML site
I tried to call this with dot, but it doesn't work. I will be thankful for help/hint.
Thing you are trying to do is to get element from dictionary using variable. Am I right ? In django template engine it's a little bit tricky, but possible. Use some template tag from this question to acomplish this
Performing a getattr() style lookup in a django template

Save output objects from django-filter to a CSV

I am have have a simple model in Django and I am using django-filters in one of my pages to have the simple functionality of having a form to search throug the models & then output a list of models and attributes.
What I need help with is how to get the set (of models data) that is selected in the django-filters form to be saved as CSV when I click 'Submit' on the form. I would also like to add a form box for how the file can be named.
models.py
class Person(..)
name = models.CharField(..)
type = models.CharField(choices=TYPECHOICES)
...
filters.py
class PersonFilter(django_filters.FilterSet):
type = django_filters.MultipleChoiceFilter(name='type', choices=TYPECHOICES)
views.py:
def query(request):
f = PersonFilter=request.GET, queryset=Person.objects.all())
return render_to_response('query.html', {'filter': f})
finally in my template I have:
{{ filter.form.as_p}}
and
{% for obj in filter %}
{% endfor %}
to put up the form & results.
Thanks
Edit:
When I do this in views, why do I iterate over ALL my objects instead of just the set specified by the form:
for obj in f:
print obj.name
This is really strange. Since in the template when I iterate over filter I only see the filtered set as per the form.
See this post: Is it possible to access static files within views.py? on how to access static files in a view. And then it would be best IMHO if the Person object would have a method like to_csv or something.
So you could just call it for every object and simply write it to the csv file.
But I'm not sure if this is really the way you want to go.
You should think about creating the graph directly from the list of objects returned by the query, since you already have your query saved.

Django template reverse url resolution without creating group for variable

I want to create urls like this;
.../film/slug-of-the-film/id-of-film
.../film/id-of-film
example;
../film/fight-club/1040
../film/1040
two links are same.
when I do like this;
url(r'^(?P<slug>[-\w]+/)?(?P<id>[0-9]+)/$', views.summary, name="film_summary")
I can reverse url from template with {% url film_summary film.slug film.id %}
I dont use slug. It is just for readability. So I try something like that;
url(r'^(?:[-\w]+/)?(?P<id>[0-9]+)/$', views.summary, name="film_summary")
but I can't reverse this from template. Is there any way to do that?
Except solutions like this; /film/{{film.slug}}/{{film.id}}
Actually I don't know is it necessary to do like that. I just aimed to don't add a parameter to view function that I won't use.
Thank you in advance :)
I would handle them as separate urls. That also simplifies the regexp for human readers.
url(r'^(?P<id>[0-9]+)/$', views.summary, name="film_summary"),
url(r'^(?P<slug>[-\w]+/)?(?P<id>[0-9]+)/$', views.summary)

Python / Django - Get List Value With Index From Object Variable Value

I have a list that is passed into a template. I want to access a value with a specific index. Problem is the list is accessed with dot notation in the template...
For example:
object = { id: 1 }
list = [ "zero", "one" ]
print list[ object.id ] ## one
Once the list is in the template you access values by index with dot notation.
list.1 ## one
list[ object.id ] ## this doesn't work
list.object.id ## this doesn't work obv.
How can I access the value "one" with the index of "1"?
Thanks in advance!
I don't think this is possible with Django's template language. It is pretty limited by design.
You can do this by putting that code in the view, and passing the value of list[object.id] down to the template when you render it.
I don't quite agree it's impossible.
You can create template tag, which will accept two arguments and will inject a new
variable into a template context.
The usage can look as follows:
{% get_list_member list object.id as list_member %}
then you can use list_member as ordinary template variable {{ list_member }}
check the implementation of standard url template tag, which also allows to assign url into
template context variable for later use.

Categories