Iterate set in template - django

I have this models:
class House(models.Model):
name = models.CharField()
class BedRoom(models.Model):
name = models.CharField()
class Catalog(models.Model):
name = models.CharField()
house = models.ForeignKey(House)
bedroom = models.ForeignKey(BedRoom)
at admin.py Catalog is inline to House
class CatalogInline(admin.TabularInline):
model = Catalog
class HomeAdmin(admin.ModelAdmin):
inline = [CatalogInline]
then I need obtain at view the list of Bedrooms from House Catalog, at Home model I have:
def bedrooms(self):
return self.catalog_set.all()
but when I do at template obtaining "houses" from a view:
{% for house in houses %}
{% for h in house %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}
I get an error:
'Catalog' object is not iterable
what I'm doing wrong?
I should define the model in a different way?

As I mentioned, you don't seem to actually be calling the bedrooms method. I guess (and it is just a guess) you mean this:
{% for house in houses %}
{% for h in house.bedrooms %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}
The bedrooms method is pointless though, as you can just as easily do this:
{% for house in houses %}
{% for h in house.catalog_set.all %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}

Related

Django templates _set.all two sub table

I have two tables I want to check if there is data or not!
Models:
class Children(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
photo = models.ImageField(blank=True, default='avatar.jpg')
class Groups(models.Model):
child = models.ForeignKey(Children, on_delete=models.CASCADE)
Templates:
{% if user.children_set.all.groups_set.all.exists %}
It's Like:
get_groups = Groups.objects.fitler(child__user=request.user).count
BUT I need this statement to be in templates, because I am trying to create for loop on User table:
{% for user in users %}
{{user.username}}
{% if user.children_set.all.groups_set.all.exists %}
Yes
{% else %}
No
{% endif %}
{% endfor %}
you can also use if condition in template if checking numbers is the ultimate goal like this:
{% if user.children_set.all.groups_set.count == 0 %}
<p>this table is empty</p>
{% else %}
<p>this table is not empty and go with the looping to print items etc<p>
{% endif %}
this may help

cannot acces foreign keys in django

I have the following template:
{% extends "artdb/base.html" %}
{% block content1 %}
<h4>Persons:</h4>
<ul>
{% for p in ans %}
<h5>First name: {{p.firstName}}</h5>
<h5>Last name: {{p.lastName}}</h5>
<h5>Phone: {{p.phoneNumber}}</h5>
<h5>Adress: {{p.streetAdress}}</h5>
<h5>Zip Code: {{p.zipcode}}</h5>
<h5>City: {{p.city}}</h5>
<hr>
{% endfor %}
</ul>
{% endblock content1 %}
{% block content2 %}
<h4>Roles:</h4>
<ul>
{% for p in ans %}
<h5>Role:{{p.persons.role}}</h5>
<hr>
{% endfor %}
</ul>
{% endblock content2 %}
and the model:
class Person(models.Model):
mail=models.EmailField()
firstName=models.CharField(max_length=200)
lastName=models.CharField(max_length=200)
phoneNumber=PhoneNumberField()
streetAdress=models.CharField(max_length=200)
zipcode=models.CharField(max_length=200)
city=models.CharField(max_length=200,default="Göteborg")
country=models.CharField(max_length=200,default="Sweden")
def __str__(self):
return "%s %s" % (self.firstName,self.lastName)
class Meta:
ordering = ('firstName','lastName')
class Role(models.Model):
role=models.CharField(max_length=200)
person=models.ManyToManyField(Person)
def __str__(self):
return self.role
class Meta:
ordering = ('role',)
But when I run the above code the only output that I get is from the block content1, i.e I cannot access the role content. I thought that role.persons.role would do it but apperantley not. There is a many-to-many relationship between perssons and roles.
Any ideas?
This should work
{% block content2 %}
<h4>Roles:</h4>
<ul>
{% for p in ans %}
{% for role in p.role_set.all %}
<h5>Role:{{ role }}</h5>
<hr>
{% endfor %}
{% endfor %}
</ul>
{% endblock content2 %}
We have to create a second for loop, since a many to many relationship will always return a list. Not a single instance. So essentially it's just like accessing a 2d array.
In Django you only have to define a n:n relationship on one end. Django will then automatically add it to the other model as well. It does this by taking the related model name and suffixing _set. So if we want to reference all of the roles attached to a person, it would be person.role_set. The other way around it would be role.person like you defined in the model.

Template not rendering correctly while iterating through foreign keys

I am trying to iterate over my FKs in my model such that I show all the connections through various tables. My template renders but does not show any values. Any ideas?
models.py
class State(models.Model):
state = models.CharField(max_length=255)
relevantdisease = models.ForeignKey(Disease)
relevantoption = models.ManyToManyField(Option, through='StateOption')
class StateOption(models.Model):
partstate = models.ForeignKey(State)
partoption = models.ForeignKey(Option)
relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')
class StateOptionOutcome(models.Model):
stateoption = models.ForeignKey(StateOption)
relevantoutcome = models.ForeignKey(Outcome)
outcomevalue = models.CharField(max_length=20)
views.py
def stateall(request, disease_id):
disease = get_object_or_404(Disease, pk=disease_id)
states = State.objects.select_related().filter(relevantdisease=disease_id)
context = {'disease':disease,'states': states}
return render(request, "stateall.html", context)
template.html
{% for state in states %}
<li>{% for i in state.stateoption_set.all %}</li>
<li>{% for j in i.stateoptionoutcome_set.all %}</li>
{% endfor %}
{% endfor %}
{% endfor %}
I would like the template to show up as:
State1<state>
<li>partoption</li>
<li>relevantoutcome: outcomevalue</li>
State2<state>
<li>partoption</li>
<li>relevantoutcome: outcomevalue</li>
...
Your template never outputs anything.
You're probably misunderstanding the use of the {% for %} template tag.
This:
<li>{% for j in i.stateoptionoutcome_set.all %}</li>
{% endfor %}
Outputs <li> a few times.
But this:
{% for j in i.stateoptionoutcome_set.all %}
<li>{{ j.relevantoutcome }}: {{ j.outcomevalue }}</li>
{% endfor %}
Will output a line per StateOptionOutcome found in i.stateoptionoutcome_set.all.

django display specific data from model in templates

Model:
class Exercise (models.Model):
name_e = models.CharField(max_length=50)
class Subject (models.Model):
name_s = models.CharField(max_length=50)
exercise = models.ForeignKey(Exercise)
View:
exercise_all = Exercise.objects.all()
subject_all = Subject.objects.all()
My SQL table contain subjects and exercises connected via ForeignKey
I pass view variables as a context to the template:
{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
{% for s_field in subject_all %}
<tr><td>{{ e_field.name_e }}</td></tr>
{% endfor %}
</table>
{% endfor %}
If I have, let's say, 3 types of Exercises and 10 Subjects connected with Exercises (subject1->exercise1, subject2->exercise1, subject3->exercise1, subject4->exercise2 etc.)
I want to display 3 tables in a template and each table will display only tr/subjects corresponding to table/exercise. I tried with {% if ... in ... %} but maybe i should do some function in view.
In this case you should be able to say:
{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
{% for s_field in e_field.subject_set.all %}
<tr><td>{{ e_field.name_e }}</td></tr>
{% endfor %}
</table>
{% endfor %}

ForeignKey, show values in template

I have two classes:
class People
name = CharField()
class Equipment
name = Charfield()
responsible = ForeignKey(People)
and view:
def persone_detail(request, tab_number):
return direct_to_template(request, 'person.html', {
'persone': Peoples.objects.filter(tab_number=tab_number)
How can I show in template the name from equipment?
By following the reverse relationship to Equipment:
http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
{% for person in persone %}
Person: {{ person.name }}
{% for equipment in person.equipment_set.all %}
Equipment: {{ equipment.name }}
{% endfor %}
{% endfor %}