简体   繁体   中英

Django: redirect to view with parameters

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. Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name. : http://dpaste.com/270YRJ9

Try using this instead

from django.urls import reverse

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

Edit

What about: return redirect('app_1:profile', user_id=userid)

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