django username in url, instead of id

后端 未结 5 710

in a mini virtual community, i have a profile_view function, so that i can view the profile of any registered user. The profile view function has as a parameter the id of th

5条回答
  •  醉梦人生
    2020-12-30 18:32

    Here's how I do it using class based generic views and the use of slugs. It's surprisingly easy and requires only a few lines of code with the help of slugs.

    # accounts/views.py
    from django.contrib.auth.models import User
    from django.views.generic.detail import DetailView
    
    class UserProfileView(DetailView):
        model = User
        slug_field = "username"
        template_name = "userprofile.html"
    
    # accounts/urls.py
    from views import UserProfileView
    urlpatterns = patterns('',
        # By user ID
        url(r'^profile/id/(?P\d+)/$', UserProfileView.as_view()),
        # By username
        url(r'^profile/username/(?P[\w.@+-]+)/$', UserProfileView.as_view()),
    )
    

    Now you can access both the user like accounts/profile/id/123/ as well as accounts/profile/username/gertvdijk/.

    What's happening here?

    • The usually required pk URL parameter is omitted and replaced by slug in the URL pattern. This is accepted by the view, because...
    • The slug parameter is being used by the DetailView (or any other SingleObjectMixin-based view) to find the object on User.username by the use of model = User and slug_field = "username". (docs)
    • Because a slug field is optional, the view is also happily serving using just the pk parameter.

提交回复
热议问题