Wednesday, August 17, 2016

How to rewrite base url in django to add logged in username in the url of all pages instead of app name?

Leave a Comment

I am working on django application and I have base url of application as below:

127.0.0.1:8000/myblog/page 

where 127.0.0.1:8000 is base url and myblog is App name and page is page name. So my requirement is to change the url to something like this without changing the internal code of my application:

127.0.0.1:8000/username/page 

Basically I want to change App name with user name in the URL. I have tried the solution given in this SO question. But it didn't helped much.

1 Answers

Answers 1

You can pass username into url regexp args and get request user from request class:
view:

def user_page(request, username):     try:         user = User.objects.get(username=username)     except User.DoesNotExists:         raise Http404     # or use shortcut get_object_or_404(User, username=username)     if request.user.username != user.username:         raise Http404     return render(request, 'templates/user_template', {'user':user}) 

urls:

url(r'^(?<username>\w+)/page/$', views.user_page, name='user_page') 

Note: username field not valid choice, if it not unique, it will produce an error when you get more then one user from User.objects.get(). Better use pk field for user page lookup.

But there is simpler way for building user page for request user. Just one url without keyword arguments, which response data for authenticated user:

view:

def user_page(request):     user = None     if request.user.is_authenticated():         user = User.objects.get(pk=request.user.pk)     return render(request, 'templates/user_template', {'user': user} ) 

urls:

url(r'^page/$', views.user_page, name='user_page') 

Now it return data based on request user or None if user is not authenticated

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment