1

In the example below, I'm trying to use the URL pattern name (ie, 'update_profile') instead of the absolute path (/profile/str:pk/update) in one of my views. This way if I later change my url path, I don't have to go an change each time I used the absolute path.

My question: how do I pass 'pk' into a pattern name? I've tried things like:

success_url = 'update_profile' % (pk)

But that doesn't seem to work.

urls.py

path('/profile/<str:pk>/update', views.ProfileUpdateView.as_view(), name='update_profile'),

views.py

def submit_profile_form(request, pk):
    
    if request.method == "POST":
        success_url = 'update_profile' //  <------ How do I pass 'pk' in here?
        ...
        return redirect(success_url)

Thanks for your help!

1 Answer 1

2

The redirect(…) function [Django-doc] accepts positional and named parameters, so you can write:

def submit_profile_form(request, pk):
    
    if request.method == "POST":
        success_url = 'update_profile'
        # …
        return redirect(success_url, pk=pk)

If the primary key is a number, you might want to use the pk path converter instead:

path(
    '/profile/<int:pk>/update',
    views.ProfileUpdateView.as_view(),
    name='update_profile'
),
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for. I knew the answer was simple. Thanks a bunch mate!

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.