我有一些问题,也许我可以在下面给出我想要实现的两个视图的例子。
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.
然后在页面上我有这些国家的列表。单击所选国家后,将打开一个新选项卡,并显示所选国家的城市列表。
所以我在循环中使用template1.html,如下所示
{% for x in list_countries %}
<li>
<a href="{% url 'some-name-url' '{{x}}' %}" class="target='_blank'">{{ x }}</a><br>
</li>
{% endfor %}
我无法通过"x"这种方式。为什么?
下一个视图的url如下所示
path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'),
我无法在href
中获得模板中给定的'x'如果Manoj的解决方案不起作用,请尝试删除单引号和{{}}。在我的程序中,我的整数不需要用{{}}包装,所以也许你的字符串也不需要。我在我的代码中有这个:
{% for item in items %}
<div class="item-title">
{{ item }}<br>
</div>
<a href="{% url 'core:edit_item' item.id %}">Edit {{ item }}</a>
{% endfor %}
它工作得很好。试一试:
<a href="{% url 'some-name-url' x %}" class="target='_blank'">{{ x }}</a>
你不需要用单引号传递这个变量。
<a href="{% url 'some-name-url' {{ x }} %}" #Just removed single quotes from variable x.
然后看它是否显示在模板
上有以下几种错误:
-
url标签只能是
x
不能是{{x}}
也不能是'{{x}}'
-
你已经在url参数(
some/countries/<str:x>/
)中传递了x
的值,并使用kwargs.get('str')
访问它,这是不正确的,它应该是kwargs.get('x')
。 -
你也没有在上下文中包括变量
countries_name
,甚至没有返回上下文。
注意:假设你已经在
template1.html
模板中获得了一些公司,这就是为什么你正在运行循环。
试试下面的代码:
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文件{% for x in list_countries %}
<li>
<a onclick="window.open('{% url 'some-name-url' x %}', '_blank')" style='cursor:pointer;'>{{ x }}</a><br>
</li>
{% endfor %}
然后你可以在template2.html中从template1.html
传入countries_name
值。
template2.html
<p>The clicked country is {{countries_name}}</p>