【问题标题】:Unable to access objects from the html无法从 html 访问对象
【发布时间】:2019-10-30 07:50:54
【问题描述】:

我正在制作一个 django 项目,并想从 html 中访问用户的特征,但无法这样做,有人可以指出我的代码中的错误吗?

html

  <img height="125px" width="125px" class="rounded-circle article-img" src="{{ user1.image.url }}">

      <h5 class='pr-2'>{{ user1.user }} </h5>

views.py

def user_blog_list(request, username):
    user1=Profile.objects.filter(user__username=username)
    context={
    'user1':user1
    }
    return render(request,'blog/user_posts.html',context)

models.py

class Profile(models.Model):
    user=models.OneToOneField(User, on_delete=models.CASCADE)
    image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True)
    description=models.TextField(max_length=200, blank=True)

    def __str__(self):
        return f'{self.user.username} Profile'

urls.py

path('user/<str:username>',views.user_blog_list,name='user-posts'),

【问题讨论】:

  • 你能添加你得到的错误吗?
  • @NotSoShabby 模板中根本没有显示任何内容
  • 尝试向 Profile 类添加 get_absolute_url 方法
  • def get_absolute_url(self): return '/user/{0}/'.format(self.username)
  • @NotSoShabby 我有一个get_absolute_url,但我不明白这与此有何关系

标签: python django


【解决方案1】:

filter 总是返回一个查询集。你需要get:

user1=Profile.objects.get(user__username=username)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多