I have some problem and maybe I can give an example of two views below what I want to achieve.
class SomeViewOne(TemplateView):
model = None
template_name = 'app/template1.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# The downloads view contains a list of countries eg France, Poland, Germany
# This returns to context and lists these countries in template1
class ItemDetail(TemplateView):
model = None
template_name = 'app/template2.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
countries_name = kwargs.get('str')
The view should get the passed "x" with the name of the country where I described it
below.
Then on the page I have a list of these countries. After clicking on the selected country, a new tab should open and show a list of cities in the selected country.
So I am using in loop template1.html as below
{% for x in list_countries %}
<li>
<a href="{% url 'some-name-url' '{{x}}' %}" >{{ x }}</a><br>
</li>
{% endfor %}
I can't pass "x" this way. Why?
The url for the next view looks like this
path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'),
And I can't get that 'x' given in the template in the href
CodePudding user response:
If Manoj's solution doesn't work, try removing the single quotes AND {{ }}. In my program, my integer doesnt need to be wrapped with {{ }}, so maybe neither does your string. I have this in my code:
{% for item in items %}
<div >
{{ item }}<br>
</div>
<a href="{% url 'core:edit_item' item.id %}">Edit {{ item }}</a>
{% endfor %}
It works just fine. Try:
<a href="{% url 'some-name-url' x %}" >{{ x }}</a>
CodePudding user response:
You don't need pass that variable with single quotes.
<a href="{% url 'some-name-url' {{ x }} %}" #Just removed single quotes from variable x.
And see if it shows on template
CodePudding user response:
There are several mistakes such as:
It should be only
x
in url tag neither{{x}}
nor'{{x}}'
you have passed the value as
x
in url params (some/countries/<str:x>/
) and accessing it usingkwargs.get('str')
which is not correct it should bekwargs.get('x')
.Also you are not including variable
countries_name
in context and not even returning context.
Note: Assuming that you are already getting some companies in
template1.html
template that's why you are running loop.
Try below code:
views.py
class ItemDetail(TemplateView):
template_name = 'template2.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['countries_name'] = self.kwargs.get('x')
return context
Template1.html file
{% for x in list_countries %}
<li>
<a onclick="window.open('{% url 'some-name-url' x %}', '_blank')" style='cursor:pointer;'>{{ x }}</a><br>
</li>
{% endfor %}
Currently you can use this passed value from template1.html to template2.html file using {{countries_name}}
.
template2.html
<p>The clicked country is {{countries_name}}</p>