How to use {{ variable }} in {% if is_exist %} in Django template? - django

Like I asked in the title, I wanna do something like the below in Django.
{% for i in "xxxxx" %}
{% if store{{ forloop.counter }} %}
...
{% endif %}
{% endfor %}
I pass variables named 'store1', 'store2', and 'store3' from views.py
However, an error happens saying
"Could not parse the remainder: '{{' from 'store{{'"
, which seems like {{ }} can't be used inside {% %}
Does anyone know how to do this?

You can't do this in the Django template language.
A better approach would be to pass the stores to the template as a list,
def my_view(request):
stores = ['store1', 'store2', ...]
return render(request, 'mytemplate.html', {'stores': stores}
then loop through the list in the template:
{% for store in stores %}
{{ store }}
{% endfor %}

Related

Django templates - get list of multiple GET param

I have a url with multiple GET params (of the same name) - mycompany.com/?a=1&a=2
When i do in django template:
{{ request.GET }}
I get:
<QueryDict: {'a': ['1', '2']}>
When i do in django template:
{{ request.GET.a }}
I get:
2
When i try to loop:
{% for a in request.GET.a %}
{{ a }}
{% endfor %}
I get:
2
How to make behave multiple GET params as list in django templates? Thx!
Template filter:
from django import template
register = template.Library()
#register.filter
def get_list(dictionary, key):
return dictionary.getlist(key)
Templates:
{% for a in request.GET|get_list:'a' %}
{{ a }}
{% endfor %}
Template filter:
[app/templatetags/exampletag.py]
from django import template
register = template.Library()
#register.filter
def get_item(dictionary, key):
return dict(dictionary).get(key)
Templates:
{% load exampletag %}
{{ request.GET|get_item:'a' }}
How to: Custom template tags and filters
A bit wonky, but does the job:
{%for list_of_elements in request.GET.lists%}
{%for element in list_of_elements.1%}
{{ element }}
{%endfor%}
{%endfor%}
Or if you only want a specific list from the query:
{%for list_of_elements in request.GET.lists %}
{%if list_of_elements.0 == "a"%}
{%for element in list_of_elements.1%}
{{ element }}
{%endfor%}
{%endif%}
{%endfor%}
{% for name, values in request.GET.lists %}
{% if name == 'a' %}{{ values|join:", " }}{% endif %}
{% endfor %}
or
{% for name, values in request.GET.lists %}
{% if name == 'a' %}
{% for value in values %}{{ value }}{% endfor %}
{% endif %}
{% endfor %}

Iterate through Django queryset within template

I have created a custom filter that returns a queryset of objects.
in: templatetags
#register.filter(name = 'create_html_for_deleting_notes')
def create_html_for_deleting_notes(task_pk):
corresponding_notes = Note.objects.filter(its_task = Task.objects.filter(pk = task_pk))
return(corresponding_notes)
in template:
{% for corresponding_task in corresponding_tasks %}
<h5>{{ corresponding_task | create_html_for_deleting_notes }}<h5/>
{% endfor %}
This works in printing out my queryset. I would like to iterate through that queryset, something like:
in template:
{% for corresponding_task in corresponding_tasks %}
{% for note in corresponding_task | create_html_for_deleting_notes %}
{{ note }}
{% endfor %}
{% endfor %}
But this gives me the error 'for statements should use the format "for x in y"'
Thank you for the help!
You need to remove the spaces around the filter | character.
However, I don't think you need the filter at all. You didn't post your model, but it seems like you have a foreignkey relationship between Task and Note, so you should just use the reverse accessor:
{% for corresponding_task in corresponding_tasks %}
{% for note in corresponding_task.note_set.all %}
{{ note }}
{% endfor %}
{% endfor %}

django templates: How to know form field type and add any buttons based on field type

I am displaying my django forms dynamically with below code.
{% for field in form %}
{% if field.field.required %}
<span class="red">*</span>
{% endif %}
{{ field.label }}:
{{ field }}
{% endfor %}
Now I want to know the datatype of fields.if field type is Datetimeinput then I want give one button beside to it to get JavaScript calender.
i want do like as below but I am not able get it
{% for field in form %}
{% if field.field.required %}
<span class="red">*</span>
{% endif %}
{% if field.field_type == 'Datetimeinput' %}
{{ field.label }}:
{{ field }}
<label>From :</label><input type="text" name="from1" class="txtbox"><input type="button" value="Cal" onclick="displayCalendar(document.forms[0].from1,'yyyy-mm-dd',this)">
{% else %}
{{ field.label }}:
{{ field }}
{% endif %}
{% endfor %}
Help me out thanks in advance.
Make a template tag. Depending on Get type of Django form widget from within template. I used this solution once or twice.
from django import template
register = template.Library()
#register.filter('klass')
def klass(ob):
return ob.__class__.__name__
In template:
{{ field.field.widget|klass }}
Will return field class name to be used in your if statements.
You could write a custom template filter for that.
#register.filter
def fieldtype(obj):
return obj.__class__.__name__
Docs on custom filters: link
However, why not just render fields without looping over them?
{{ form.birthdate }}
Then you'll know for sure what is what.

What is the best way to get in my template second/threeth object?

def myview(request):
myobj = MyObject.objects.all()
return render_to_response('x.html',{'myobj': myobj}, context_instance=RequestContext(request))
and
{% for o in myobj %}
{{o.test}}
{% endfor %}
What is the best way to get in my template second/threeth object?
for has forloop attribute:
{% for o in obj_queryset %}
{% if forloop.counter == 2 %}Second{% else %}
{% if forloop.counter ==3 %}Third{% endif %}
{{ o.test }}
{% endif %}
{% endfor %}
If you are just looking for the 2nd object from the queryset (and not print anything else), you can simply look up the second object (see the docs for more about this):
{{ obj_queryset.2 }}
Note that in your example, myobj isn't an object (ie. a model instance), it's a queryset.

Dictionary with arrays in django templates

I have dictionary with arrays inside:
dicarr = {'category': ['post1','post2', 'e.g.'], 'category2': ['post1','post2']}
Array is filled in one cycle:
dicarr = {}
for category in Categories.objects.all():
category_posts = Post.objects.filter(category=category)
dicarr[category] = [post for post in category_posts ]
How can i get access to array from django template? I tried:
{% for arrdic in dicarr %}
{{ arrdic.name }}
{% for i in arrdic.posts %}
{{ i.name }}
{% endfor %}
{% endfor %}
But isn't working.
Assuming you have a foreign key pointing to Category on your Post, you don't even need to do it this complicated. All you need to is pass this to the template:
categories = Category.objects.all()
Then you can iterate like this in the template:
{% for category in categories %}
{{ category.name }}
{% for post in categories.post_set.all %}
{{ post.name }}
{% endfor %}
{% endfor %}
You can do this with any foreign key relationships. Hope that answers your question!
Following your original code, your template should be (also see for tag docs):
{% for category, posts in dicarr.items %}
{{ category.name }}
{% for post in posts %}
{{ post.name }}
{% endfor %}
{% endfor %}
But this isn't the best way to do this, because your view will produce number of queries equal to the number of categories. See my answer to a similar question for a more efficient solutions.