Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to redirect with arguments

Tags:

python

django

After submit a form, I want to redirect to an specific view passing one flag=True in order to activate a popup like:

def view1(request):
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            form.save()
            return redirect('new_view') # Here I need to send flag=True
    else:
        form = Form()
        return render(request, 'template.html', {'form': form})

How can I do this?

like image 666
P. Rodoreda Avatar asked Feb 25 '18 09:02

P. Rodoreda


People also ask

Can we pass data with redirect in Django?

You can now perform a redirect with Django, either by using the redirect response classes HttpResponseRedirect and HttpResponsePermanentRedirect , or with the convenience function django. shortcuts. redirect() .

Can we pass context in redirect?

I would use session variables in order to pass some context through a redirect. It is about the only way to do it outside of passing them as part of the url and it is the recommended django option.

What does return redirect do in Django?

redirect()Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: A model: the model's get_absolute_url() function will be called. A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.

What is the difference between redirect and render in Django?

The render function Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. You request a page and the render function returns it. The redirect function sends another request to the given url.


2 Answers

It's not quite clear on what you mean by arguments if it should be in the query string or arguments to a view.

Either way, below is both solutions;

redirect accepts args and kwargs

redirect('new_view', flag='show') # This is the argument of a view

or

redirect('{}?flag=True'.format(reverse('new_view'))

Then you can access it in the view like so

show_flag = bool(request.GET.get('flag', False))
like image 186
Henrik Andersson Avatar answered Sep 25 '22 14:09

Henrik Andersson


for a given url pattern such as

url(r'^random/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.random, name="urlname")

or

url(r'^argfree/', views.random2, name="urlname2

from django.http import HttpResponseRedirect
from django.urls import reverse

def view(request):
    # do your thing
    if something:
        return HttpResponseRedirect(reverse("urlname", args=["this_is_arg1", "this_is_arg2"]))
    else:
        return  HttpResponseRedirect(reverse("urlname"))
like image 44
Işık Kaplan Avatar answered Sep 22 '22 14:09

Işık Kaplan