I have a template from which I need to render information from multiple models. My models.py look something like this:
# models.py
from django.db import models
class foo(models.Model):
''' Foo content '''
class bar(models.Model):
''' Bar content '''
I also have a file views.py, from which I wrote according to this Django documentation and the answer given here, and looks something like this:
# views.py
from django.views.generic import ListView
from app.models import *
class MyView(ListView):
context_object_name = 'name'
template_name = 'page/path.html'
queryset = foo.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['bar'] = bar.objects.all()
return context
and my urlpatterns on urls.py have the following object:
url(r'^path$',views.MyView.as_view(), name = 'name'),
My question is, on the template page/path.html how can I reference the objects and the object properties from foo and bar to display them in my page?
{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
To access foos from your template, you have to include it in the context:
# views.py
from django.views.generic import ListView
from app.models import *
class MyView(ListView):
context_object_name = 'name'
template_name = 'page/path.html'
queryset = foo.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['bars'] = bar.objects.all()
context['foos'] = self.queryset
return context
Now in your template you can access the value by referencing the key that you used when creating the context dictionary in get_context_data
:
<html>
<head>
<title>My pathpage!</title>
</head>
<body>
<h1>Foos!</h1>
<ul>
{% for foo in foos %}
<li>{{ foo.property1 }}</li>
{% endfor %}
</ul>
<h1>Bars!</h1>
<ul>
{% for bar in bars %}
<li>{{ bar.property1 }}</li>
{% endfor %}
</ul>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With