database query via django orm in template - django

<ul>
{% for staff in staff_list %}
<li>{{ staff|title }}<br>
{% for person in movie.staff.all %}
{{ person }}<br>
<img src="{{ person.photo.url }}"></li>
{% endfor %}
{% endfor %}
</ul>
I iterate over the list "staff_list" and want to take from the model "movie" the field that is in the variable "staff", but orm django calls the field "staff", but I do not have such a field, and therefore nothing is returned. How to call the data that is in the "staff" variable and not call the "staff" field

Another solution could be to build the template dataset in view and then loop it in template.
Datalogic should be happening in view and template should focus on rendering.
A dictionary with person and related movies should be build in view.

Related

How to filter a ManyToMany field from django template?

I have a model named Universities in which there is a ManyToMany field named bookmarks associated with User model. In template file, I have looped through all the universities {% for university in universities %} and I am trying to show a bookmark icon based on the logged in user has bookmarked that specific university or not. However, it seems like I can not filter the query in template directly. How do I do that?
Don't name your models with plural names. "universities" should be "university" because every instance of the model represents a single university.
You can access one to many and many to many relationships in the templates. How you do that depends if you have assigned a related_name to the relationship.
Let me show you an example:
class University(models.Model):
name = models.CharField(max_length=50)
bookmarks = models.ManyToManyField(Bookmark, on_delete="models.CASCADE", related_name="universities")
Then you pass a list of all university models to the template:
class MyView(View):
def get(self, request):
context = { 'universities' : University.objects.all() }
return render(request, "mytemplate.html", context)
And finally you access all that you need from the template. This part is slightly tricky but not too much.
{% for university in universities %}
{% for bookmark in university.bookmarks.all %}
{{ bookmark }}
{% endfor %}
{% endfor %}
If you were to instead pass to the template a list of Bookmark instances, then you would have used the related_name stated in our example.
So like this:
{% for bookmark in bookmarks %}
{% for university in bookmark.universities.all %}
{{ university }}
{% endfor %}
{% endfor %}
If you didn't specify a related_name, then you can access the same data using the _set convention:
{% for bookmark in bookmarks %}
{% for university in bookmark.university_set.all %}
{{ university }}
{% endfor %}
{% endfor %}

Modifying property of checkbox elements with respect to Django model data

Problem
I have a django model named 'Task' which is related to a model called 'List' (A list has several tasks). I have appended all the 'Task' objects of all 'List' objects in an array 'tasks'. The Task object has a boolean member 'completed' which is true if the task is completed and false if not.
Now, in the template I want to iterate the array 'tasks' and find all those tasks which are completed and change the state of their check-boxes as 'checked' through their IDs (checkbox ID format : task). How do I do it?
Code
I have tried the following django template code with JavaScript but its not working apparently.
<script>
{% for list_tasks in tasks %}
{% for task in list_tasks %}
{% if task.completed == True %}
document.getElementById("task{{task.id}}").checked=true;
{% endif %}
{% endfor %}
{% endfor %}
</script>
Instead of doing it in JavaScript, you can directly do it in the html.
For example:
{% for list_tasks in tasks %}
{% for task in list_tasks %}
<input type="checkbox" {% if task.completed %} checked {% endif %} />
<label for="task{{task.id}}"> Task name </label>
{% endfor %}
{% endfor %}
But if you update your question with how you display these checkboxes, I could help more.
Also, another option would be to create a form with dynamic firlds directly in django. This is a good article on how to do it: https://jacobian.org/2010/feb/28/dynamic-form-generation/

Display all model fields in template

I am trying to display all the fields of a model called company as a list in my template. But can't seem to make it work.
Code
<ul>
{% for field in company.fields.all %}
<li>{{ fields.name }}</li>
{% endfor %}
</ul>
You can get list of fields with
company._meta.get_fields()
But you can not access _meta attribute in template, because it starts with _. So, you can assign _meta or result of get_fields() to variable with legal name in view, or return list of fields from your custom template filter.
Example with view:
return render(request, 'your_template.html', {
'company': company,
'company_fields': company._meta.get_fields()
})
and in template:
{% for field in company_fields %}
{{ field.att_name }}
{% endfor %}

django ModelChoiceField: how to iter through the instances in the template?

I am trying to get access to the instances of a ModelChoiceField to render them the way I want in a template by displaying several fields of the instances.
class MyForm(forms.Form):
mychoices = forms.ModelChoiceField(
queryset=ObjectA.objects.all(), widget=forms.RadioSelect(), empty_label=None
)
This does not work:
{% for choice in form.mychoices %}
{{ choice.pk}}
{% endfor %}
I also tried to use the queryset but it does not render anything
{% for choice in form.mychoices.queryset %}
{{ choice.pk}}
{% endfor %}
Any idea?
Thanks
{% for choice in form.mychoices.field.queryset %}
{{ choice.pk }}
{% endfor %}
Notice the extra .field. It's a bit strange the first time you come across it, but it gives you what you want. You can also access the choices attribute of that object, instead of accessing queryset directly, but you'll need to access the first element of the choice to get the PK of the instance, like this:
{% for choice in form.mychoices.field.choices %}
{{ choice.0 }}
{% endfor %}

what is the right way to query a manytomany field in django

so i have a model which is,
class Category(SmartModel):
item=models.ManyToManyField(Item)
title=models.CharField(max_length=64,help_text="Title of category e.g BreakFast")
description=models.CharField(max_length=64,help_text="Describe the category e.g the items included in the category")
#show_description=check box if description should be displayed
#active=check box if category is still avialable
display_order=models.IntegerField(default=0)
def __unicode__(self):
return "%s %s %s %s " % (self.item,self.title, self.description, self.display_order)
and as you may see, it has a manytomany field
item=models.ManyToManyField(Item)
i want to return all the items in a template, here is my views.py for this
def menu(request):
categorys= Category.objects.all()
items= categorys.all().prefetch_related('item')
context={
'items':items,
'categorys':categorys
}
return render_to_response('menu.html',context,context_instance=RequestContext(request))
here is how am doing it in the templates,
<ul>
{% for item in items %}
<li>{{ item.item }}
</li>
</ul>
{% endfor %}
after all this,this is what it is returning in my web page,
<django.db.models.fields.related.ManyRelatedManager object at 0xa298b0c>
what am i doing wrong,I have really looked around but all in vain, hoping you can help me out and thanking you in advance
Exactly, you have a many to many manager. You need to actually query something... like all()
{% for item in items %}
{% for i in item.item.all %}
{{ i }}
{% endfor %}
{% endfor %}
Based on your variable naming, I think you're confusing the results of prefetch_related as a bunch of items. It is in fact returning a QuerySet of Category objects.
So it would be more intuitive to call them categories.
{% for category in categories %}
{% for item in category.item.all %}
{{ item }} {# ...etc #}
Try to use:
categorys= Category.objects.prefetch_related('item').all()
And then in template:
{% for category in categorys %}
{% for item in category.item.all %}
{{ item }}
{% endfor %}
{% endfor %}