在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。如果我需要为数据库中的特定用户而不是登录用户提取数据,此模型将如何工作?

xiezhanliang 回答:在Django中访问其他用户的信息

由于您的错误消息说show_profile期望再有1个参数username,因此您需要在url模式中传递用户名:

 path('<str:username>/show_profile/',views.show_profile,name='show_profile'),
本文链接:https://www.f2er.com/3170036.html

大家都在问