Redirect while passing message in django

2024/10/2 3:25:36

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.usersettings.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'),
Answer

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 = Noneif( '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 messagingreturn render(request,'template_name.html', {'message_disp':message })
https://en.xdnf.cn/q/70897.html

Related Q&A

Django sorting by date(day)

I want to sort models by day first and then by score, meaning Id like to see the the highest scoring Articles in each day. class Article(models.Model):date_modified = models.DateTimeField(blank=True, n…

ImportError: No module named pynotify. While the module is installed

So this error keeps coming back.Everytime I try to tun the script it returns saying:Traceback (most recent call last):File "cli.py", line 11, in <module>import pynotify ImportError: No …

business logic in Django

Id like to know where to put code that doesnt belong to a view, I mean, the logic.Ive been reading a few similar posts, but couldnt arrive to a conclusion. What I could understand is:A View is like a …

Faster alternatives to Pandas pivot_table

Im using Pandas pivot_table function on a large dataset (10 million rows, 6 columns). As execution time is paramount, I try to speed up the process. Currently it takes around 8 secs to process the whol…

How can I temporarily redirect the output of logging in Python?

Theres already a question that answers how to do this regarding sys.stdout and sys.stderr here: https://stackoverflow.com/a/14197079/198348 But that doesnt work everywhere. The logging module seems to …

trouble with creating a virtual environment in Windows 8, python 3.3

Im trying to create a virtual environment in Python, but I always get an error no matter how many times I re-install python-setuptools and pip. My computer is running Windows 8, and Im using Python 3.3…

Python imaplib search email with date and time

Im trying to read all emails from a particular date and time. mail = imaplib.IMAP4_SSL(self.url, self.port) mail.login(user, password) mail.select(self.folder) since = datetime.strftime(since, %d-%b-%Y…

cumsum() on multi-index pandas dataframe

I have a multi-index dataframe that shows the sum of transactions on a monthly frequency. I am trying to get a cumsum() on yearly basis that respects my mapid and service multi-index. However I dont kn…

Python SSL Certification Problems in Tensorflow

Im trying to download the MNIST data which is supposedly handled in: tensorflow.examples.tutorials.mnist.input_data.read_data_sets() As far as Im aware read_data_sets sends a pull request to a server t…

How do I get a python program to run instead of opening in Notepad?

I am having some trouble with opening a .py file. I have a program that calls this .py file (i.e. pathname/example.py file.txt), but instead of running the python program, it opens it in Notepad. How t…