Django how to do a conditional redirect after POST?

django redirect
django redirect with parameters
django redirect to another view
django redirect to another url
httpresponseredirect
django redirect to previous page
django redirect to same page
django redirect with context

I have a form that displays some of the fields in the user profile among other things. In this form the fields from the profile are disabled. If the details are outdated the user can go to the edit profile view and update the details. For this, I included a button in the template of the form. After updating the profile I want the user to return to the form. This last part is the one I am having problems with.

The link to edit the profile from the form looks like:

<a class="btn btn-outline-info" href="{% url 'profile'%}?next={% url 'submission_resume' %}">Edit Profile</a>

This is how the url looks comming from the form:

http://127.0.0.1:8000/users/profile/?next=/submissions/resume/

The problem is that in the edit profile view I do not know how to implement the conditional redirect:

def profile(request):
    """ View and edit the profile. It requires user to be login """
    if request.method == 'POST':
        form = UserModifyForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your account has been updated!')
            #??? if next in url go back to the form ???
            #??? return redirect(???) ???
            #??? else: ???
            return redirect('profile')
    else:
        form = UserModifyForm(instance=request.user)
 #--> Dict for template with the forms
    context = {
        'form': form,
    }
 #--> Show profile page
    return render(request, 'user_profile.html', context)   
#---

Use this:

redirect_to = request.POST.get("next", "profile")
return redirect(redirect_to)

The Ultimate Guide to Django Redirects – Real Python, To use HttpResponseRedirect you have to import it from django.http module. the URLs, we can also use reverse() method with HttpResponseRedirect to can also pass a Model object like, Post or Category to the redirect()� to redirect to the same page (e.g. an http GET) after a POST, I like return HttpResponseRedirect("") # from django.http import HttpResponseRedirect it also avoids hardcoding the show:detail route name, and is a lil' clearer intention wise (for me at least!)


I managed to make this work by changing the view to:

def profile(request):
    """ View and edit the profile. It requires user to be login """
    if request.method == 'POST':
        form = UserModifyForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your account has been updated!')
            redirect_to = request.POST['redirect_to']
            return redirect(redirect_to)
    else:
        redirect_to = request.GET.get("next", "profile")
        form = UserModifyForm(instance=request.user)
 #--> Dict for template with the forms
    context = {
        'redirect_to': redirect_to,
        'form'       : form,
    }
 #--> Show profile page
    return render(request, 'user_profile.html', context)   
#---

and in the template including:

<input type="hidden" name='redirect_to' value="{{redirect_to}}">

inside the <form> tag

But still I wonder if there is an easier way to do this.

Redirecting URLs in Django, GET and POST are the only HTTP methods to use when dealing with forms. or do other processing before sending an HTTP redirect to the browser telling it useful as a template variable, but could be useful in conditional tests such as:. In the above example, first we imported redirect from django.shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments.


request.POST.get('redirect_to', None))

The above statement will give the redirect_to value if it present, else it will return 'None'

so you can try

request.POST.get('redirect_to', 'replace the value with default view where you want to redirect'))

You can also try below code if you simply want to redirect to the previous page

 redirect(request.META.get('HTTP_REFERER'))

Working with forms | Django documentation, by if you redirect after a multipart/form-data post. This bug is avoidable if request.POST is not accessed outside of a "if request.method == 'POST':" conditional,� from django.shortcuts import redirect from simple_blog.models import Post def post_view (request, post_id): post = Post. objects. get (pk = post_id) return redirect (post) # equivalent to: return HttpResponseRedirect(post.get_absolute_url()) A reverse url name (accept view arguments);


#9140 (bug in django.http.multipartparser.MultiPartParser after , Combines a given template with a given context dictionary and returns an HttpResponse object with You can use the redirect() function in a number of ways. How do I send a conditional message in Django? My app doesn't require the users to enter an email ID while signing up. However, I want the users to add it to their profile anyway, albeit at their own leisure.


Django shortcut functions | Django documentation, You can use Django's URL routing to create easy to read URLs that can keep up with the /learn/ route, and then the post's slug, the lowercase title with dashes. validators): """ Calls get_object_or_404 and conditionally builds redirect URL� They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.


Create Human Readable URLs in Django That Don't Break, The authentication system is very flexible, and you can build up your URLs, forms , views, and p> {% endif %} {% endif %} <form method="post" action="{% url ' login' Redirect to home URL after login (Default redirects to As you can see, we use if - else - endif template tags to conditionally display text� Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.