How to display in template value of foreign key? - django

models:
class ProductOpinion(models.Model):
user = models.ForeignKey(User)
product = models.ForeignKey(Product)
point = models.IntegerField()
class Product(models.Model):
name = models.CharField(max_length=255)
How to display in my template point of my ProductOpinion?
def index(request):
products = Product.objects.all()
return render_to_response('index.html',{'products':products}, context_instance=RequestContext(request))
template:
{% for p in products %}
{{ p.point }}
{% endfor %}

If yout want to acces the point field you have to do something like this:
{% for p in products %}
{% for productoption in p.productoptions_set.all %}
{{ productoption.point }}
{% endfor %}
{% endfor %}

You need to use:
{{ p.productopinion_set.all }}

Related

How i can compare models in template

Why this compare code not work? I want to display all departments where departments filial = filial, but i got failure only. Thanks very much for you answers!
{% for filial in filials %}
{{ filial }}
{% for dep in departments %}
{{ dep }}
{% if dep.Filial == filial.pk %}
IFIFIFIFIF{{ dep.fullname }}
{% endif %}
{% endfor %}
<br>
{% endfor %}
models:
class Filials(models.Model):
Fullname=models.CharField(max_length=30,blank=False)
Entity=models.CharField(max_length=20,blank=True)
City=models.CharField(max_length=15,blank=True)
INN = models.IntegerField(max_length=20,blank=True,null=True)
def __str__(self):
return self.Fullname
def get_absolute_url(self):
return f'/{self.id}'
class Department(models.Model):
Filial=models.ForeignKey(Filials, on_delete=models.CASCADE,related_name='department', blank=True)
Fullname = models.CharField(max_length=30,blank=False)
def __str__(self):
return self.Fullname

combining two or more querysets from different models in django

Main model:
class MainCategory(models.Model):
title = models.CharField(max_length=120, unique=True)
App#1:
class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
main_category = models.ForeignKey(MainCategory, default=1, related_name='car_category')
App#2:
class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
main_category = models.ForeignKey(MainCategory, default=1, related_name='classifieds_category')
on home page I want a combined list of both category list items as follows.
{% for object in main_cat_list %}
{{ object.title }}
{% for item in object.car_category %}
{{ item.title }}
{% endfor %}
{% endfor %}
How I can insert classifieds category also inside this list?
If you merely want to also display the classified_category as you have the car_category.
{% for object in main_cat_list %}
{{ object.title }}
{% for item in object.car_category %}
{{ item.title }}
{% endfor %}
{% for item in object.classified_category %}
{{ item.title }}
{% endfor %}
{% endfor %}

django view - all categories and all entries

I'm trying to build a page with all of the model's categories and associated entries in one view. I followed tips from here django class based views for all categories with all entires and here Get all categories and items in category but I still can't get it to work. Any ideas ?
-- models
class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Feed(models.Model):
name = models.CharField(max_length=100)
url = models.CharField(max_length=100)
category = models.ForeignKey(Category)
user = models.ManyToManyField(User)
def __unicode__(self):
return self.url
-- views
def category_page(request):
object_list = Category.objects.all()
context = {'object_list': object_list,}
return render(request, 'category_page.html', context)
-- template category_page.html
{% block content %}
{% for category in object_list %}
{{ category.name }}
{% for entry in category.entry_set.all %}
{{ category.name}}
{% endfor %}
{% endfor %}
{% endblock content %}
I'm getting list of all categories displayed but no entries.
thanks
-M
Here
{% for entry in category.entry_set.all %}
{{ category.name}}
{% endfor %}
should be
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{{ category.name}} inside the forloop for entries is what is not displaying the correct name.
Also, what is entry_set ? If you are not specifying a related_name, you need to use the lower-case model name to get the related objects (feed_set in this case).
Something like this:
category.feed_set.all
Summing it up,
{% block content %}
{% for category in object_list %}
{{ category.name }}
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{% endfor %}
{% endblock content %}
You can read more on related objects here
If this is your actual code, the problem is variable names in your template.
{% for category in object_list %}
{{ category.name }}
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{% endfor %}
Specifically, you refer to entry_set, but that's not the reverse name for the relationship since your model name is Feed rather than Entry and you haven't declared a non-default related_name argument.
Also, you're re-printing your category name instead of the name of the Feed instances.

Total Count In Django

I have models, views & template in Django and want to display the total count of category.
class Entry (models.Model):
title = models.CharField(max_length=200)
category = models.ForeignKey('entry.Category')
class Category(models.Model):
title = models.CharField(max_length=100)
parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
def category(request):
category = Category.objects.all()
return render_to_response('category.html', locals(), context_instance=RequestContext(request))
<ul>
{% for category in category %}
<li>{{ category.title }} ({{ category.entry_set.all.count }})</li>
{% endfor %}
</ul>
Current output:
-Category 1 (0)
--Sub Category 1 (3)
--Sub Category 2 (6)
And desire output is like this:
-Category 1 (9)
--Sub Category 1 (3)
--Sub Category 2 (6)
How to get that output?
Use category.entry_set.count instead of category.entry_set.all.count.
Also, you are using same variable name category for referencing multiple values, you may want to change that.
Update template as:
<ul>
{% for cat in category %}
<li>{{ cat.title }} ({{ cat.entry_set.count }})</li>
{% endfor %}
</ul>
Solved by using Django-MPTT and update my view & template like this:
views.py:
def category(request):
category = Category.tree.add_related_count(Category.objects.all(), Entry, 'category', 'cat_count', cumulative=True)
return render_to_response('category.html', locals(), context_instance=RequestContext(request))
category.html:
{% recursetree category %}
<ul>
{{ node.title }} ({{ node.cat_count }})
{% if not node.is_leaf_node %}
<li class="children">
{{ children }}
</li>
{% endif %}
</ul>
{% endrecursetree %}

ForeignKey. How to get data?

class Property(models.Model):
title = models.CharField(max_length=255)
class CurrentPrice(models.Model):
current = models.ForeignKey(Current)
prop = models.ForeignKey(Property)
price = models.DecimalField(max_digits=5, decimal_places=2)
class Current(models.Model):
name = models.CharField(max_length=20)
views.py:
...
p = Property.objects.all()
return render_to_response('index.html',{'p':p},context_instance=RequestContext(request))
How to get price of Property and display it in my template?
template:
{% for item in p %}
{{ item.title }}
{{ item.price }} # ???
{% endfor %}
I'm not sure what is your purpose/design of models, which doesn't look appropriate from what you have shown.
You will have many CurrentPrice per Property object, so in template you can do is
{% for item in p %}
{{ item.title }}
{% for cp in item.currentprice_set.all %}
{{ cp.price }}
{% endfor %}
{% endfor %}
If Property can have multiple CurrentPrice objects (what is by default):
{% for item in p %}
{{ item.title }}
{% for current_price in item.currentprice_set.all %}
{{ current_price.price }}
{% endofor %}
{% endfor %}
If only one (but in that case it is better to use o2o field instead of the FK fiel else it is up on you to prevent multiple CurrentPrice records pointing to the same Property):
{% for item in p %}
{{ item.title }}
{{ item.currentprice_set.get.price }}
{% endfor %}
I think what you're trying to do is something like that below.
class Property(models.Model):
title = models.CharField(max_length=255)
#property
def current_price(self):
# The current price is the last price that was given.
if self.pricing_history.count() > 0:
return self.pricing_history.order_by('-when')[0].amount
return None
class Price(models.Model):
prop = models.ForeignKey(Property, related_name='pricing_history')
amount = models.DecimalField(max_digits=5, decimal_places=2)
when = models.DateTimeField(auto_now_add=True)
example in template:
{% for item in p %}
{{ item.title }}
{{ item.current_price }}
{% endfor %}