我在模板中有一个循环:
{% for article in user.article_set.all %}
{{ article.article_date }}
{{ article.article_title }}
{{ article.article_cost }}
{% endfor %}
如何显示该周期中所有{{ article.article_cost }}
的总和(不计算)?或者我需要在我的观点中写点什么?
我试过了,但我不知道如何在我的模板中使用它,所以我不知道,这是否有效:
u = User.objects.get(username=username)
total_price = u.article_set.all().annotate(total=Sum('article_cost'))
完整视图:
def userprofile(request, username):
u = User.objects.get(username=username)
total_price = u.article_set.all().annotate(total=Sum('article_cost'))
if request.POST:
user_form = UserForm(request.POST, instance=request.user)
user_profile = UserProfileForm(request.POST, request.FILES, instance=request.user.profile)
if user_form.is_valid():
user_form.save()
if user_profile.is_valid():
user_profile.save()
else:
user_form = UserForm(instance=request.user,
initial={
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'email': request.user.email,
})
user = request.user
profile = user.profile
user_profile = UserProfileForm(instance=profile)
return render_to_response('profile.html', {'user_form': user_form, 'user_profile': user_profile}, context_instance=RequestContext(request))