You have almost got it right. Just change
return render(request, 'polls/productpage.html', {
'product': product
}, {
'image': image
})
to
return render(request, 'polls/productpage.html', {
'product': product,
'image': image
})
Last Updated : 02 Nov, 2021,GATE CS 2021 Syllabus
Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in django.
How to Create Basic Project using MVT in Django ?
How to Create an App in Django ?
After creating this model, we need to run two commands in order to create database for the same.
python manage.py makemigrations python manage.py migrate
By both the methods you will see the same output. Let’s check what is there on http://localhost:8000/, before doing this don’t forget to add some data to your model.
How to add data to your model
Django ORM– Inserting, Updating & Deleting Data
Built-in class-based generic views,Class-based views Built-in class-based generic views ,Using Django Class-based views Built-in class-based generic views , Django 4.1 documentation Using Django Class-based views Built-in class-based generic views
# models.py
from django.db
import models
class Publisher(models.Model):
name = models.CharField(max_length = 30)
address = models.CharField(max_length = 50)
city = models.CharField(max_length = 60)
state_province = models.CharField(max_length = 30)
country = models.CharField(max_length = 50)
website = models.URLField()
class Meta:
ordering = ["-name"]
def __str__(self):
return self.name
class Author(models.Model):
salutation = models.CharField(max_length = 10)
name = models.CharField(max_length = 200)
email = models.EmailField()
headshot = models.ImageField(upload_to = 'author_headshots')
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length = 100)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE)
publication_date = models.DateField()
# views.py
from django.views.generic
import ListView
from books.models
import Publisher
class PublisherListView(ListView):
model = Publisher
# urls.py from django.urls import path from books.views import PublisherListView urlpatterns = [ path('publishers/', PublisherListView.as_view()), ]
{% extends "base.html" %}
{% block content %}
<h2>Publishers</h2>
<ul>
{% for publisher in object_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
{% endblock %}
# views.py
from django.views.generic
import ListView
from books.models
import Publisher
class PublisherListView(ListView):
model = Publisher
context_object_name = 'my_favorite_publishers'
from django.views.generic
import DetailView
from books.models
import Book, Publisher
class PublisherDetailView(DetailView):
model = Publisher
def get_context_data(self, ** kwargs):
# Call the base implementation first to get a context
context = super().get_context_data( ** kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context
Sometimes, your template need a bit more of information. For example, we would like to have the user in the header of the page, with a link to their profile next to the logout link. In these cases, use the get_context_data method.,You need to call get_context_data method on the super class and it will return the default context instance. Any item that you add to this dictionary will be available to the template., Django Class Based Views: Example of CreateView , Django Class Based Views: Example of CreateView
views.py
class BookView(DetailView):
template_name = "book.html"
def get_context_data(self, ** kwargs)
""
" get_context_data let you fill the template context "
""
context = super(BookView, self).get_context_data( ** kwargs)
# Get Related publishers
context['publishers'] = self.object.publishers.filter(is_active = True)
return context
book.html
<h3>Active publishers</h3>
<ul>
{% for publisher in publishers %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
Once you have a Template object, you can render multiple contexts through it. For example:,Once you have a Template object, you can pass it data by giving it a context. A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags.,In Python and in the Django template system, these objects evaluate to False in a Boolean context:,Whenever you’re using the same template source to render multiple contexts like this, it’s more efficient to create the Template object once, and then call render() on it multiple times:
Let’s start with a simple example template. This Django template describes an HTML page that thanks a person for placing an order with a company. Think of it as a form letter:
<html>
<head><title>Ordering notice</title></head>
<body>
<h1>Ordering notice</h1>
<p>Dear {{ person_name }},</p>
<p>Thanks for placing an order from {{ company }}. It's scheduled to
ship on {{ ship_date|date:"F j, Y" }}.</p>
<p>Here are the items you've ordered:</p>
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if ordered_warranty %}
<p>Your warranty information will be included in the packaging.</p>
{% else %}
<p>You didn't order a warranty, so you're on your own when
the products inevitably stop working.</p>
{% endif %}
<p>Sincerely,<br />{{ company }}</p>
</body>
</html>
In code, here’s what that looks like:
>>> from django
import template
>>>
t = template.Template('My name is {{ name }}.') >>>
c = template.Context({
'name': 'Adrian'
}) >>>
print t.render(c)
My name is Adrian. >>>
c = template.Context({
'name': 'Fred'
}) >>>
print t.render(c)
My name is Fred.
Let’s go through some template system basics:
>>> from django.template
import Template
>>>
t = Template('My name is {{ name }}.') >>>
print t
If you’re following along interactively, you’ll see something like this:
<django.template.Template object at 0xb7d5f24c>
A context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values. Call the Template object’s render() method with the context to “fill” the template:
>>> from django.template
import Context, Template
>>>
t = Template('My name is {{ name }}.') >>>
c = Context({
'name': 'Stephane'
}) >>>
t.render(c)
u 'My name is Stephane.'
Here’s an example of template compilation and rendering, using a template similar to the example in the beginning of this chapter:
>>> from django.template import Template, Context
>>> raw_template = """<p>Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
>>> t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"
Let’s go through some template system basics:
>>> from django.template
import Template
>>>
t = Template('My name is {{ name }}.') >>>
print t
If you’re following along interactively, you’ll see something like this:
<django.template.Template object at 0xb7d5f24c>
When you create a Template object, the template system compiles the raw template code into an internal, optimized form, ready for rendering. But if your template code includes any syntax errors, the call to Template() will cause a TemplateSyntaxError exception:
>>> from django.template import Template
>>> t = Template('{% notatag %}')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
...
django.template.TemplateSyntaxError: Invalid block tag: 'notatag'
A context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values. Call the Template object’s render() method with the context to “fill” the template:
>>> from django.template
import Context, Template
>>>
t = Template('My name is {{ name }}.') >>>
c = Context({
'name': 'Stephane'
}) >>>
t.render(c)
u 'My name is Stephane.'
Here’s an example of template compilation and rendering, using a template similar to the example in the beginning of this chapter:
>>> from django.template import Template, Context
>>> raw_template = """<p>Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
>>> t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"
Once you have a Template object, you can render multiple contexts through it. For example:
>>> from django.template
import Template, Context
>>>
t = Template('Hello, {{ name }}') >>>
print t.render(Context({
'name': 'John'
}))
Hello, John
>>>
print t.render(Context({
'name': 'Julie'
}))
Hello, Julie
>>>
print t.render(Context({
'name': 'Pat'
}))
Hello, Pat
Whenever you’re using the same template source to render multiple contexts like this, it’s more efficient to create the Template object once, and then call render() on it multiple times:
# Bad for name in ('John', 'Julie', 'Pat'): t = Template('Hello, {{ name }}') print t.render(Context({ 'name': name })) # Good t = Template('Hello, {{ name }}') for name in ('John', 'Julie', 'Pat'): print t.render(Context({ 'name': name }))
This is best illustrated with a few examples. For instance, suppose you’re passing a Python dictionary to a template. To access the values of that dictionary by dictionary key, use a dot:
>>> from django.template
import Template, Context
>>>
person = {
'name': 'Sally',
'age': '43'
} >>>
t = Template('{{ person.name }} is {{ person.age }} years old.') >>>
c = Context({
'person': person
}) >>>
t.render(c)
u 'Sally is 43 years old.'
Similarly, dots also allow access of object attributes. For example, a Python datetime.date object has year, month, and day attributes, and you can use a dot to access those attributes in a Django template:
>>> from django.template
import Template, Context
>>>
import datetime >>>
d = datetime.date(1993, 5, 2) >>>
d.year
1993
>>>
d.month
5
>>>
d.day
2
>>>
t = Template('The month is {{ date.month }} and the year is {{ date.year }}.') >>>
c = Context({
'date': d
}) >>>
t.render(c)
u 'The month is 5 and the year is 1993.'
This example uses a custom class, demonstrating that variable dots also allow attribute access on arbitrary objects:
>>> from django.template
import Template, Context
>>>
class Person(object):
...def __init__(self, first_name, last_name):
...self.first_name, self.last_name = first_name, last_name >>>
t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.') >>>
c = Context({
'person': Person('John', 'Smith')
}) >>>
t.render(c)
u 'Hello, John Smith.'
Finally, dots are also used to access list indices, for example:
>>> from django.template
import Template, Context
>>>
t = Template('Item 2 is {{ items.2 }}.') >>>
c = Context({
'items': ['apples', 'bananas', 'carrots']
}) >>>
t.render(c)
u 'Item 2 is carrots.'
Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']) and then a method call (upper()):
>>> from django.template
import Template, Context
>>>
person = {
'name': 'Sally',
'age': '43'
} >>>
t = Template('{{ person.name.upper }} is {{ person.age }} years old.') >>>
c = Context({
'person': person
}) >>>
t.render(c)
u 'SALLY is 43 years old.'
Django multiple templates in single view,Django how to get multiple context_object_name for multiple queryset from single view to single template,django generic view send context to multiple templates at the same time,Django multiple formsets in a single view only saves last value entered
Well, you can basically check what's in the gameslug
variable before rendering.
def game_detail(request, tournamentslug, lolslug, gameslug): game = get_object_or_404( LeagueofLegendsGame, tournament__tournament_slug = tournamentslug, lol_slug = lolslug, tournament__game__slug = gameslug ) context = { 'game': game, } if gameslug == 'lol': template = 'template1.html' elif gameslug == 'heartstone': template = 'template2.html' #else render the one you 're already rendering else: template = 'esports/lolgame.html' return render(request, template, context)