Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect while passing message in django

I'm trying to run a redirect after I check to see if the user_settings exist for a user (if they don't exist - the user is taken to the form to input and save them).

I want to redirect the user to the appropriate form and give them the message that they have to 'save their settings', so they know why they are being redirected.

The function looks like this:

def trip_email(request):
    try:
        user_settings = Settings.objects.get(user_id=request.user.id)
    except Exception as e:
        messages.error(request, 'Please save your settings before you print mileage!')
        return redirect('user_settings')

This function checks user settings and redirects me appropriately - but the message never appears at the top of the template.

You may first think: "Are messages setup in your Django correctly?"

I have other functions where I use messages that are not redirects, the messages display as expected in the template there without issue. Messages are integrated into my template appropriately and work.

Only when I use redirect do I not see the messages I am sending.

If I use render like the following, I see the message (but of course, the URL doesn't change - which I would like to happen).

def trip_email(request):
    try:
        user_settings = Settings.objects.get(user_id=request.user.id)
    except Exception as e:
        messages.error(request, 'Please save your settings before you print mileage!')
        form = UserSettingsForm(request.POST or None)
        return render(request, 'user/settings.html', {'form': form})

I have a few other spots where I need to use a redirect because it functionally makes sense to do so - but I also want to pass messages to those redirects.

The user_settings function looks like this:

def user_settings(request):
    try:
        user_settings = Settings.objects.get(user_id=request.user.id)
        form = UserSettingsForm(request.POST or None, instance=user_settings)
    except Settings.DoesNotExist:
        form = UserSettingsForm(request.POST or None)
    if request.method == 'POST':
        settings = form.save(commit=False)
        settings.user = request.user
        settings.save()
        messages.warning(request, 'Your settings have been saved!')

    return render(request, 'user/settings.html', {'form': form})

I can't find anything in the documentation saying that you can't send messages with redirects... but I can't figure out how to get them to show.

Edit: This is how I render the messages in the template:

{% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message }}
  </div>
{% endfor %}

I'm not sure if it matters - but it looks like it's almost calling 'GET' twice from somewhere.

is calling get twice like this normal?

the URL section looks like this for these two URLS:

# ex: /trips/email
url(r'^trips/email/$', views.trip_email, name='trip_email'),
# ex: /user/settings
url(r'^user/settings/$', views.user_settings, name='user_settings'),
like image 929
Hanny Avatar asked Jun 27 '17 16:06

Hanny


People also ask

Why is Django redirecting me to the login page?

When you are not logged-in and request a URL that requires authentication, like the Django admin, Django redirects you to the login page. When you log in successfully, Django redirects you to the URL you requested originally.

What is an unvalidated redirect in Django?

This kind of redirect is called an open or unvalidated redirect. There are legitimate use cases for redirecting to URL that is read from user input. A prime example is Django’s login view. It accepts a URL parameter next that contains the URL of the page the user is redirected to after login.

What happens when I Change my Password in Django?

When you log in successfully, Django redirects you to the URL you requested originally. When you change your password using the Django admin, you are redirected to a page that indicates that the change was successful.

How to display messages after form submit in Django?

Display messages after form submit in Django is not difficult as it seems to be. Here are the simple steps to implement message framework for your Django website. 1. Initialize the Messages App in Django Settings Add django.contrib.messages app entry in Django INSTALLED_APPS list in settings.py.


1 Answers

Nope I think the best way is to use your sessions.

from django.contrib import messages << this is optional if you choose to use django messaging

Handle your form

def handle_form(request):
    ...
    request.session['form_message'] = "success or fail message here"

    redirect('/destination/', {})

def page_to_render_errors():
    ...
    message = None
    if( 'form_message' in request.session ):
        message = request.session['form_message']
        del request.session['form_message']
        messages.success(request, message ) #<< rememeber messages.success() along with messages.info() etc... are method calls if you choose to pass it through django's messaging

    return render(request,'template_name.html', {'message_disp':message })
like image 143
A H Bensiali Avatar answered Sep 26 '22 04:09

A H Bensiali