首页 > 解决方案 > 在 django 中访问不同用户的信息

问题描述

我知道要访问我们使用的登录用户的数据request.user。我的目标是列出表格中的所有用户并链接到他们的个人资料页面。如何使链接转到用户的个人资料页面?

我有以下内容:

# app/views.py
def tutors_list(request):
  user_list = CustomUser.objects.all()
  context = {
    'user_list': user_list
  }  
  return render(request, 'tutors_list.html', context)

def show_profile(request, username):
  user = CustomUser.objects.get(username = username) ### NOT DISPLAYING RIGHT USER
  #user = CustomUser.objects.get(id=id)
  context = {
    'user': user
  }  
  return render(request, 'show_profile.html', context)


# myproject/urls.py
url_patterns = [
  # ...
  path('show_profile/', views.show_profile, name='show_profile'),
  # ...

我收到一条错误消息,说show_profile期望再有 1 个参数,username. 如果我需要为数据库中的特定用户而不是登录用户提取数据,该模型将如何工作?

标签: django

解决方案


正如您的错误所说 show_profile,预计还有 1 个参数,username所以您需要在您的 url 模式中传递用户名:

 path('<str:username>/show_profile/', views.show_profile, name='show_profile'),

推荐阅读