Home > other >  Django not Redirecting due to Page not Found Error
Django not Redirecting due to Page not Found Error

Time:07-29

I am creating an edit profile function that updates the profile and redirects back to the profile page of the current user. Currently, the updating works fine, but the redirection is giving me a page not found error. Why is that happening?

url patterns:

urlpatterns = [
    path('change-profile/', users_views.change_profile, name='change_profile'),
    path('user/<str:username>/', UserProfileView.as_view(), name='user-profile'),
    ...
]

views.py

@login_required
def change_profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, 'Profile Updated')
            return redirect('user-profile', {'username':request.user.username})
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form' : u_form,
        'p_form' : p_form
    }
    return render(request, 'users/change_profile.html', context)

Error messageenter image description here

CodePudding user response:

The redirect(…) function [Django-doc] uses named parameters, not a dictionary, so:

return redirect('user-profile', username=request.user.username)

You have sent {'username': 'TestPWRS' } as username, and (likely) there is no user with that username, only a user with username TestPWRS.

  • Related