【问题标题】:View Profile page as another user in django在 django 中以另一个用户身份查看个人资料页面
【发布时间】:2016-12-13 15:48:14
【问题描述】:

所以我有一个my user profile 视图,您可以作为登录用户查看。我想添加第二个视图,以便其他已登录的用户也可以访问个人资料页面,但我不确定我的做法是否正确

urls.py

url(r'^accounts/profile/', main_views.uprofile, name='uprofile'), #the page you see as my profile
    url(r'^profile/(?P<pk>\d+)/$', main_views.oprofile, name='oprofile'), # the page i use so other users can view the profile page
    url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), #Custom update profile page

main_views.py

@login_required(login_url='/accounts/login/')
def uprofile (request):

    context = locals()  
    template = 'profile.html'
    return render (request, template, context)

def oprofile (request, pk):
    user = User.objects.get(pk=pk)

    context = locals()  
    template = 'profile.html'
    return render (request, template, context)

【问题讨论】:

  • 这听起来很宽泛,但我想你只需要在模板中包含一些布尔值来隐藏任何编辑功能
  • 没有人可以编辑,因为登录的 ID 需要很多用户 ID ...我正在寻找更有效的方法。
  • 我认为你不会比单个布尔值更有效。到目前为止,您尝试过什么?

标签: django django-views


【解决方案1】:

从产品的角度来看,您可能希望为uprofileoprofile 保留相同的网址。一个简单的原因是,当我访问我的个人资料时,如果我想与其他人分享,我只需复制粘贴网址即可。

怎么做?

在您看来,传递一个标志,帮助您的模板呈现正确的元素。例如,如果用户与正在访问的配置文件相同,则传递一个标志,例如editable,并使用它来显示编辑按钮。您可以使用单个视图,而不是两个视图。

此外,人们倾向于记住他们的用户名/句柄,而不是 id。所以最好有用户名。但是,请确保您对所有用户都有唯一的用户名。

urls.py

url(r'^profile/(?P<username>[\w\-]+)/$', main_views.profile, name='profile'),

views.py

def profile (request, username):
    # If no such user exists raise 404
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404

    # Flag that determines if we should show editable elements in template
    editable = False
    # Handling non authenticated user for obvious reasons
    if request.user.is_authenticated() and request.user == user:
        editable = True

    context = locals()
    template = 'profile.html'
    return render (request, template, context)

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 2023-03-30
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多