2014-07-02 68 views
0

我试图建立用户配置文件在我的网站,所以我们有:做用户配置文件在Django中

www.example.com/someuser

www.example.com/anotheruser2

在我的urls.py

url(r'^(?P<profile>[0-9A-Fa-f]{1,36})/', 'site.views.profile), 

和我的观点

def profile(request, profile): 
    ... do something ... 

有两个问题:

  1. 这是为了做到这一点,正确的做法还是有更好的办法?
  2. 我应该如何处理其他网址,如“关于我们”等

对于第2点,我会做:

url(r'^aboutus/', 'site.views.aboutus'), 
url(r'^(?P<profile>[0-9A-Fa-f]{1,36})/', 'site.views.profile), 

所以,现在的个人资料将是一切都在别人的包罗万象网站,我必须检查一个有效的配置文件,然后抛出404如果没有找到密码。

再一次,有没有更好的方法来做到这一点?

回答

0

这不是用site.views.profile作为一个包罗万象的一个好主意。这不是很好的责任分离,它不应该是它的工作。怎么样这样的事情,而不是:

url(r'^profile/$', 'site.views.profile_self'), 
url(r'^profile/(?P<profile_name>[0-9A-Fa-f]{1,36})/$', 'site.views.profile'), 
url(r'^aboutus/', 'site.views.aboutus'), 

对于包罗万象,使用自定义404错误页面,或者你可以让服务器提出一个404错误。

+0

我看到瓦特/这个解决方案是我有问题建立www.example.com/profile/someuser要求是www.example.com/someuser – Paul

+0

如果这是一个*硬性要求*,那么你就没有选择的余地,除了做你建议。但这是糟糕的设计,因为它妨碍你正确地分开责任。 – janos

0

账户/ models.py

from django.db import models 

class User(): 
    def get_profile(self): 
     return UserProfile.objects.get_or_create(user_id=self.id) 

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    # another fields 

账户/ urls.py

url(r'^profile/$', 'site.views.profile'), 

账户/ views.py

from django.contrib.auth.decorators import login_required 

@login_required 
def profile(request): 
    # get current logged user profile 
    profile = request.user.get_profile() 

通过这种方式,只有用户登录才能看到他自己的档案。

对于第2点,这有什么问题?

url(r'^about_us/$', 'site.views.about_us'), 

--UPDATE--

啊,OK。那么,你是对的。但为什么不用用户名?

账户/ urls.py

url(r'^(?P<username>[-\w]+)/$', 'site.views.profile'), 
+0

我看到瓦特/这个解决方案的问题是,我将不得不建立www.example.com/profile/someuser要求是www.example.com/someuser – Paul

相关问题