简体   繁体   中英

Django url pk + slug page not found

I'm using django allauth for user authentication and so far I have been able to display user's page like this: account/1/trial/, where 1 is the pk number and trial is the username(unique), or like this: account/1/. In both cases everything works fine, but if I want to show only the username (account/trial/) in the url than I can't load the profile (accounts/profile/) page for the logged in user(404). Probably my profile function is wrong, how can I correct it so that the page will load normally as if using pk in urls.

urls:

(r"^(?P<pk>\d+)/(?P<slug>[\w.@+-]+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), #if I use this url the page loads correclty

(r"^(?P<pk>\d+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), # also with this url it works

(r"^(?P<slug>[\w.@+-]+)/$", DetailView.as_view(context_object_name='detail',slug_field = "username",model=User,template_name='account/user_detail.html'), name='detail_view'), #if I use only the slug the page does not load.

(r"^profile/$", views.profile, name="profile_view"), #this is the profile page url

and the profile page view:

def profile(request):
    return render_to_response("account/profile.html",locals(),context_instance=RequestContext(request))

The string "profile" matches the regex for the slug-only username view, and since Django matches URLs in order, a request for the URL "profile/" will always go to that view instead. The simple solution is to move the profile URL above the other one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM