Python 如何在模板中的类内显示来自函数的循环?
我想用“a”中的值创建一个表,但函数在类中:Python 如何在模板中的类内显示来自函数的循环?,python,django,Python,Django,我想用“a”中的值创建一个表,但函数在类中: # Views.py class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' def get_graph_sales_year_month(self): data = [] try: year = datetime.now().year
# Views.py
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'
def get_graph_sales_year_month(self):
data = []
try:
year = datetime.now().year
for m in range(1, 13):
total = Sale.objects.filter(date_joined__year=year, date_joined__month=m).aggregate(
r=Coalesce(Sum('iva'), 0)).get('r')
data.append(float(total))
except:
pass
return data
# And I got a lot of others self functions
def get_test(request):
a = ['hola','chau','como','va']
#return a
return render(request, 'dashboard.html', {'name': a})
# HTML template
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th><span>Date</span></th>
</tr>
</thead>
<tbody>
{% for i in name %}
<tr>
<td><span>{{i}}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
但我希望该函数在类中,因为我在URL.py调用所有类:
path('dashboard/', DashboardView.as_view(), name='dashboard'),
我想要这样的东西:
谢谢
编辑
我在课堂上得到了很多自我功能 您好,您可以在基于函数的视图中执行此操作,这在您的案例中更简单
from django.contrib.auth.decorators import login_required
path('dashboard/', get_test, name='dashboard'),
@login_required
def get_test(request):
a = ['hola','chau','como','va']
return render(request, 'test.html', {'name': a})
您需要将上下文覆盖到
TemplateView
的get\u context\u data
方法。检查一下
编辑:
另外,按照Abdul的建议,检查extra_context
方式。您可以添加一些上下文作为类属性,也可以直接在url声明中添加。看
作为属性:
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'
extra_context = {'a': ['hola','chau','como','va']}
在url中:
path(
'dashboard/',
DashboardView.as_view(extra_context={'a': ['hola','chau','como','va']}),
name='dashboard',
),
可以重写在基于类的视图中返回的上下文数据 使用 像这样的
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
a = ['hola','chau','como','va']
context['name'] = a
return context
还要提到可以在类上设置的
extra_context
属性(如果这个额外的上下文不应该是动态的)@AbdulAzizBarkat谢谢,将其添加到回答中谢谢,我错过了第一部分。它起作用了。当做很好用,非常感谢!谢谢但是我忘了提到我在课堂上还有其他的自我功能。当做
path(
'dashboard/',
DashboardView.as_view(extra_context={'a': ['hola','chau','como','va']}),
name='dashboard',
),
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
a = ['hola','chau','como','va']
context['name'] = a
return context