0

I've got a function based view in Django called userView

@login_required(login_url='/login/')
def userView(request):
    user = None
    if request.user.is_authenticated():
        user = request.user
        user_id = user.pk


    return render(request, "user_view.html", {'user': user})

and here's my URL for it

urlpatterns = [
     url(r'^user/', userView, name='user'),
]

After my user has logged in, I'd like him to see his pk number in the URL. I.e., if the user's PK is 3 and the user directs their browser to www.myapp.com/user, the URL in the address bar should change to www.myapp.com/user/3/. How do I make that happen? I'm aware I need to edit the RegEx for the URL into

url(r'^user/(?P<user_id>[0-9]+)/$', userView, name='user')

but how do I pass the PK number to the URL?

6
  • Not quite clear what you're asking. That URL already requires a user_id, so you can't get to that view without having it in the first place. Commented Aug 19, 2016 at 10:47
  • I edited the post to make it clearer. How do I pass the pk number to the url from the view Commented Aug 19, 2016 at 10:58
  • 1
    I still don't really understand. You're presumably redirecting from login to this view, why can't you put the number into that redirect URL? Commented Aug 19, 2016 at 11:01
  • So when the user directs their browser to www.myapp.com/user/ you want the URL to change to www.myapp.com/user/3/ (if the user's PK is 3)? Commented Aug 19, 2016 at 11:04
  • @das-g, yes that's exactly right. Commented Aug 19, 2016 at 11:23

1 Answer 1

2

I am not a Django expert but my guess is you want to redirect the user to his 'home page' after he is logged in. That can be done using the redirect() method

@login_required(login_url='/login/')
def userLoginView(request):
    if request.user.is_authenticated():
        return redirect("/user/{0}".format(request.user.pk), user=request.user)

And then define a second view that will render the home page

def userView(request, user_id=None, user=None):
    return render(request, "user_view.html", {'user': user})

Also your url patterns should be as follows

urlpatterns = [
     url(r'^user/', userLoginView, name='userlogin'),
     url(r'^user/(?P<user_id>[0-9]+)/$', userView, name='user')
]
Sign up to request clarification or add additional context in comments.

1 Comment

Even better to use Django's reverse lookup. With your urlpatterns it would look something like: return redirect(reverse('user', kwargs={'user_id': request.user.pk})). That way, if you would ever change your urlconf from user/<id> to, say, profile/<id>, all your redirects still work. See here for details: docs.djangoproject.com/en/1.10/ref/urlresolvers/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.