我使用{extends 'xxx.html'}
使所有模板都具有相同的' head'并且'尾部'在头部有一个用户头像区域{{ avatar }}
,但我使用相同的方法在每个视图中传递此avatar
,我的index.html可以& #39;正确显示头像,但另一个可以,所以我认为我的索引视图有问题。
这是索引视图:
def index(request):
if request.method == 'GET':
all_user = UserInfo.objects.all()
user = all_user.filter(username=request.user.username)
return render(request, 'index.html', {
"icon": user.icon,
"user": user.username,
})
这里有一些可以正确显示头像的观点:
if request.user.is_authenticated():
my_fav = UserFavorite.objects.all()
my_fav_num = my_fav.filter(user=request.user).count()
my_posts_num = all_posts.filter(user=request.user).count()
my_msg = UserMessage.objects.all()
my_msg_num = my_msg.filter(user=request.user, has_read=False).count()
all_user = UserInfo.objects.all()
user = all_user.get(username=request.user.username)
return render(request, 'community.html', {
"all_posts": posts,
"post_num": post_num,
"animal_kind": animal_kind,
"post_kind": post_kind,
"sort": sort,
"my_fav_num": my_fav_num,
"my_posts_num": my_posts_num,
"my_msg_num": my_msg_num,
"icon": user.icon,
"user": user.username,
})
else:
my_fav_num = 0
my_msg_num = 0
my_posts_num = 0
return render(request, 'community.html', {
"all_posts": posts,
"post_num": post_num,
"animal_kind": animal_kind,
"post_kind": post_kind,
"sort": sort,
"my_fav_num": my_fav_num,
"my_posts_num": my_posts_num,
"my_msg_num": my_msg_num,
})
HTML code:
<div class="head_bar" style="z-index: 1;">
<a class="logo" href="{% url 'index' %}">Nostray</a>
<div class="nav_bar">
<a class="nav" href="{% url 'adopt:market' %}"><span class="roll" id="adopt">领养</span></a>
<a class="nav" href="{% url 'community:allpost' %}"><span class="roll" id="community">社区</span></a>
<a class="nav" href=""><span class="roll" id="charity">公益</span></a>
</div>
{% if request.user.is_authenticated %}
<div class="current_user"><a href="">
<img src="{{ MEDIA_URL }}{{ icon }}" title="登录状态:{{ user }}" class="curr_icon">
</a></div>
{% else %}
<button class="bar_btn1" onclick="location.href={% url 'login' %}">登录</button>
<button class="bar_btn2" onclick="location.href={% url 'registe' %}">注册</button>
{% endif %}
无法理解为什么索引无法找到头像。
答案 0 :(得分:2)
在index
您的用户列表中,但在您的正确显示中&#39; user是单个对象,它有attrs,你需要替换
user = all_user.filter(username=request.user.username)
on
user = all_user.get(username=request.user.username)
# ^^^^