Display all model fields in template - django

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

Related

database query via django orm in template

<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.

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

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

Django getting properties of model dynamically

I have a model like
class Document(models.Model):
comment = models.TextField(null=True,blank=True)
upload_date = models.DateTimeField(blank=False)
Document objects are listed in a template as
{% for doc in doc_list %}
{{ doc.comment }}
{{ doc.upload_date }}
{% endfor %}
However, I'd like to reach the properties of doc dynamically like
{{ doc."comment" }}
or
{{ doc|getField:"comment" }}
How can I do that?
Thanks
I assume you mean you want to access fields on a model by using another variable, which you don't necessarily know at the time. So you might have some_var be passed into the template, and this is the field in the model that you'd like to display, such as comment or upload_date.
You could build a template tag to do this:
#register.simple_tag
def get_model_attr(instance, key):
return getattr(instance, key)
Now in your template you can do stuff like:
{% for doc in doc_list %}
{% get_model_attr doc "comment" %}
{% get_model_attr doc some_var %}
{% endfor %}

List products by category in Django template

What's the best way to generate HTML which has a heading for each Category, and Products under that category in a Django template?
I toyed with the idea of having a passing a dictionary, or an ordered list...
Take a look at the regroup template filter
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
With it you could do something like this:
{% regroup products by category as products_by_category %}
{% for c in products_by_category %}
<h1>{{c.grouper}}</h1>
<ul>
{% for p in c.list %}
<li>{{p.name}}</li>
{% endfor %}
</ul>
{% endfor %}
In addition to what #Wade suggests you can also add a method to your Category model to return the products it has.
Example..
class Category:
...
...
def get_products(self):
return Product.objects.filter(category=self)
Then in a template you can..
{% for category in categories %} # assuming categories is passed from the view.
{% for product in category.get_products %}
...
used a sorted list in the view code,
sorted(dom_obj.objects.all(), key=lambda d: d.sort_key)
and then used the filter tag
{% ifchanged %}<h1>{{ prod.cat }}</h1>{% endifchanged %}