Django: redirect to view with parameters

Question:

I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'

app_1/urls.py:

url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),

app_1/views.py (things I’ve also tried are commented):

def index(request):
    userid = request.user.profile.id
    #return render(request, 'app_1/index.html', context)
    #return profile(request, request.user.profile.id)
    #return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
    #return redirect(profile, user_id= request.user.profile.id)
    return redirect('profile', user_id=userid)


def profile(request, user_id):
    user = get_object_or_404(Profile, pk=user_id)
    return render(request, 'app_1/user_prof.html', {'user': user})

I must be missing something because this should be easy but I’m stuck on it. Thanks in advance.

EDIT: The error I’m getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9

Answers:

Try using this instead

from django.urls import reverse

return redirect(reverse('profile', kwargs={"user_id": userid}))

Or this:

return redirect('app_1:profile', user_id=userid)
Answered By: NS0
return redirect('profile', user_id=coverage_id)
Answered By: user18609885
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.