Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect in Django with context?

I have a view that validates and saves a form. After the form is saved, I'd like redirect back to a list_object view with a success message "form for customer xyz was successfully updated..."

HttpResponseRedirect doesn't seem like it would work, because it only has an argument for the url, no way to pass dictionary with it.

I've tried modifying my wrapper for object_list to take a dict as a parameter that has the necessary context. I the return a call to this wrapper from inside the view that saves the form. However, when the page is rendered, the url is '/customer_form/' rather than '/list_customers/'. I tried modifying the request object, before passing it to the object_list wrapper, but that did not work.

Thanks.

like image 440
Kevin Avatar asked Sep 02 '10 06:09

Kevin


People also ask

Can I pass context with redirect Django?

In django You can not pass parameters with redirect. Your only bet is to pass them as a part of URL.

How do I redirect in Django?

In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. In the above example, first we imported redirect from django.

Can we send 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() .

What is the difference between HttpResponseRedirect and redirect?

There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.


1 Answers

request.user.message_set was deprecated in Django 1.2 and has been removed since Django 1.4, the message framework should be used instead.

from django.contrib import messages  # messages.add_message(request, level, message, extra_tags='', fail_silently=False) messages.add_message(request, messages.INFO, "Your Message") 

Alternatively, you can use one of the shortcut functions:

from django.contrib import messages  messages.debug(request, "Your Message") messages.info(request, "Your Message") messages.success(request, "Your Message") messages.warning(request, "Your Message") messages.error(request, "Your Message") 

Messages can then be rendered on the template with:

{% if messages %}     <ul class="messages">         {% for message in messages %}             <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>         {% endfor %}     </ul> {% endif %} 
like image 185
Antoine Pinsard Avatar answered Oct 24 '22 10:10

Antoine Pinsard