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?
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() .
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.
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.
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.
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))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With