【发布时间】:2019-01-14 13:08:50
【问题描述】:
大家好,我想用 django 完成我的项目 如何让头像出现在所有项目模板上的问题
如果头像显示在一个模板中,例如:www.site.com/index 另一个不起作用 www.site.com/page2/page3 ...... 请帮帮我,因为我对此感到厌倦了
这是我的model.py
class author(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(blank=True, upload_to='Avatar')
def __str__(self):
return self.name
class articles(models.Model):
article_author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
avatar = models.ForeignKey(author, on_delete=models.CASCADE)
base.html
<!-- when loggedin -->
{% if request.user.is_authenticated %}
<li class="nav-item dropdown my-2">
<a class="nav-link dropdown-toggle " data-toggle="dropdown" href="" id="themes" > {{full_name}} <span class="caret"></span>
<img class="rounded-circle" src="{{ user.author.profile_picture.url }}" style="max-width: 2em; margin-right: 10px;"> </a>
<div class="dropdown-menu" aria-labelledby="themes">
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/profile/">profile</a>
<a class="dropdown-item" href="/create/" >add post</a>
<a class="dropdown-item" href="#" style="margin-top: 1em;" data-toggle="modal" data-target="#exampleModal">logOut</a>
</div>
</li>
{% else %}
<!-- end loggedin -->
views.py
# open home page
def index(request):
authorUser = get_object_or_404(author, name=request.user.id)
all_articles = articles.objects.all().order_by('-id')
solo = articles.objects.order_by('-id')[:1]
solo1 = articles.objects.order_by('-id')[:3]
#show five articles plus read
article_read = articles.objects.order_by('id')[:5]
#show spicial articles
# show first article
first = articles.objects.order_by('-id')[:10]
# show fourth articles
fourth = articles.objects.order_by('-id')[:4]
return render(request, 'home/index.html', {
'full_name': request.user.username,
'first_article':first,
'fourth_article':fourth,
'all_articles': all_articles,
'five_articles': article_read,
'solo': solo,
'solo1': solo1,
'user': authorUser
})
【问题讨论】:
-
您可以在所有模板中简单地使用
request.user.author.profile_picture.url。 -
base.html 包含导航栏和页脚,但其他模板不包含导航栏结束页脚
-
@Selcuk 不,你不能,这是从作者到用户的外键,所以你必须这样做
request.user.author_set.first.profile_picture.url。 -
@DanielRoseman 你是绝对正确的。在这种情况下,模型看起来有点奇怪,因为当同一用户有多个
author实例时,get_object_or_404会失败。我建议将其更改为OneToOne关系而不是ForeignKey。 -
谢谢你,现在它可以工作了丹尼尔罗斯曼