【问题标题】:how can i display other user information in django如何在 django 中显示其他用户信息
【发布时间】:2019-06-12 13:52:58
【问题描述】:

我正在创建一个用户可以查看其他用户个人资料的网站,但问题是当用户输入另一个用户个人资料时,它会显示他的个人信息

这是 urls.py 文件代码

urlpatterns = [
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
]

这是view.py文件代码

class UserPostListView(ListView):
    model = Post = Profile
    template_name = 'website/user_posts.html'

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user)

    def get_username_field(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Profile.objects.filter(user=user)

这是models.py文件

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    age = models.IntegerField(verbose_name='Ålder', default=15, 
    blank=True)

    def get_absolute_url(self):
        return reverse('user_posts', kwargs={'pk': self.pk})

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

user_posts.html 文件

{{ user.get_full_name }}
{{ user.profile.age }}
{{ view.kwargs.username }}

在模板中显示了用户名,但没有显示姓名和年龄。

【问题讨论】:

  • 我使用的是 2.1.5 django 版本

标签: django django-models django-rest-framework django-templates django-views


【解决方案1】:

user 始终是当前登录用户。您的视图使用 Profile 模型,因此您可以访问 profileobject

{{ profile.user.get_full_name }}
{{ profile.age }}

请注意,您的 get_username_field 方法永远不会被调用并且不会执行任何操作;你应该删除它。

另请注意,将age 作为整数存储在数据库中确实不是一个好主意。这意味着您必须以某种方式每年更新它,因为人们有变老的奇怪习惯......最好存储出生日期,并有一种显示年龄的方法。

【讨论】:

  • 不是必须是{{ profile.user.get_full_name }}吗?
  • 感谢您提供的非常有用的好信息,但即使在我输入 {{ profile.age }} 之后,它也没有显示我使用 2.1.5 django 版本的年龄
【解决方案2】:

首先你的 get_username_field 没有用。

在你的views.py中,

class UserPostListView(ListView):
    model = Profile
    template_name = 'website/user_posts.html'
    context_object_name = 'user_content'  
    allow_empty = False  #this will show 404 if the username does not exists

    def get_queryset(self):
        return User.objects.filter(username=self.kwargs['username']) 
        # you can do it in one line now 

现在用 html 显示这个,

{% for user in user_content %}
{{user.get_full_name}}
# rest of your code
{% endfor %}

您还可以按照上述相同的方式显示该特定用户的帖子。

【讨论】:

  • '找不到带有参数'('',)'的'用户帖子'的反向。尝试了 1 种模式:['user/(?P[^/]+)$']' 我收到此错误
猜你喜欢
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2014-05-25
  • 2012-08-29
相关资源
最近更新 更多