3

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.

Community
  • 1
  • 1
Always_a_learner
  • 4,585
  • 13
  • 63
  • 112
  • 2
    https://docs.djangoproject.com/ja/1.9/topics/http/urls/ You will be able to get the URL params in your view. You can take it from there. –  Aug 05 '16 at 05:20

1 Answers1

9

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

Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75