2016-12-13 40 views
0

因此,我有一个my user profile视图,您可以以登录用户身份查看。我想添加第二个视图中用户可以访问个人资料页以及因此其他记录,但我真的不知道我在做正确的方式查看个人资料页面作为django中的其他用户

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) 
+0

这听起来很广,但我想像你只需要在模板中包括隐藏任何一些布尔编辑功能 – Sayse

+0

没有人可以编辑,因为登录ID需要很多用户ID ......我正在寻找更有效的方式来完成此操作。 – LeLouch

+0

我不认为你会比单个布尔变得更有效率。你试过什么了? – Sayse

回答

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)