Dictionary with arrays in django templates - django

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.

Related

Django showing values of an annotated queryset without knowing the filed name

I´m building a dashboard where you can cross data from a sales database.
For example, sales by seller, products by client, etc. I let the user choose both option 1 and option 2.
I get the form back to the view and annotate the model with those options:
if filter_opts.is_valid():
option_1 = filter_opts.cleaned_data["option_1"]
option_2 = filter_opts.cleaned_data["option_2"]
results = ventas.values(option_2).annotate(Count(option_1, distinct=True))
The annotation works fine and if I just print the queryset in the template
{% for case in results %}
{{ case }}
{% endfor %}
I can see it like:
{'cliente': '502 EMSUR', 'prod_nombre__count': 9}
Then in the template I want to show only the values. But I can´t tell forehand which would be the value name to do something like this:
{% for case in results %}
{{ case.option_1 }}
{{ case.option_2 }}
{% endfor %}
If I iterate over the result I can see the field name:
{% for case in results %}
{% for item in case %}
{{ item }}
{% endfor %}
{% endfor %}
How can I show the values of that fields?
Thanks!
Since each case in results is a dictionary, you can use the property .items inside the template to iterate through its keys and values:
{% for case in results %}
{% for item, value in case.items %}
{{ item }} - {{ value }}
{% endfor %}
{% endfor %}

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

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 %}

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 %}

set_all to get value from custom model manager in django

I have two models:
Tutorial
--> consist of published manager which returns queryset when is_published=True
Category
In template, I am passing Category object.
{% for category in categories %}
{% for tutorial in category.tutorial_set.all %}
{{ tutorial.title }}
{% endfor %}
{% endfor %}
Instead of getting all, I want to get from published manager like: Tutorials.published.all()
How to achieve this?
Well I guess you can do something like
class TutuorialManager(models.Manager):
def published(self):
return self.filter(is_published = True)
then in the views you can do something like..
{% for category in categories %}
{% for tutorial in category.tutorial_set.published.all %}
{{ tutorial.title }}
{% endfor %}
{% endfor %}

Django: For Loop to Iterate Form Fields

I don't want to use django's built in form generation, seeking to specify each field in my template in order to customize the html output.
How do I iterate over a series of form fields?
If my form looks like this:
class MyForm(forms.Form):
main_image = forms.ImageField()
second_image = forms.ImageField()
third_image = forms.ImageField()
fourth_image = forms.ImageField()
...
Is there way to write a {% for %} loop so that I can iterate through:
{{ form.main_image }}
{{ form.second_image }}
{{ form.third_image }}
{{ form.fourth_image }}
I tried the following which seemed logical, but did not work:
{% for field in form %}
{{ form.field }}
{% endfor %}
Well this would clearly not work:
{% for field in form %}
{{ form.field }}
{% endfor %}
but this will:
{% for field in form %}
{{ field }}
{% endfor %}
The best way is to use two loops, one for hidden fields and one for visible fields :
visibles:
{% for field in form.visible_fields %}
{{ field.label }}
{{ field }}
{% endfor %}
hiddens:
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
in this way you will have better control over UI elements.
This one should work :
{% for field in form %}
{{ field }}
{% endfor %}
Once you loop through field in form , you can't access form.field
For any frontend developers looking to customize a Django form you can use a package called django-widget-tweaks to render fields individually. Example code below:
{# Your template with the form #}
{% extends "base.html" %}
{% load widget_tweaks %}
<form action="" method="POST">
{% csrf_token %}
{% for field in form %}
<label for="{{ field.id_for_label }}">
{{ field.label }}{% if field.field.required %}*{% endif %}
</label>
{% render_field field %}
{% endfor %}
<button type="button">
Submit Form
</button>
</form>
Note: You'll want to make this look nicer of course, and you may want to loop through your form errors if there are any.
They have some very useful examples on their PyPi page as well.