Doing User Profiles In Django

徘徊边缘 提交于 2020-01-06 10:52:31

问题


I'm trying to set up user profiles in my site so we have:

www.example.com/someuser

www.example.com/anotheruser2

in my urls.py

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

and my view:

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

There are two questions:

  1. Is this the correct way to do this or is there a better way?
  2. How should I handle other urls, like "aboutus", etc.

For Point 2, I would do:

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

So now profile will be the catchall for everything else in the site, and I have to check for a valid profile then throw a 404 if a password is not found.

Again, is there a better way to do this?


回答1:


It's not a good idea to use site.views.profile as a catchall. It's not good separation of responsibilities, it shouldn't be its job. How about something like this instead:

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'),

For the catchall, use a custom 404 page, or you could let the server raise a 404 error.




回答2:


accounts/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

accounts/urls.py

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

accounts/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()

this way the user logged only can see his own profile.

and for the point 2, what's wrong with this?

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

--UPDATE--

ah, ok. then, you are right. but why not with the username?

accounts/urls.py

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


来源:https://stackoverflow.com/questions/24537179/doing-user-profiles-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!