Search code examples
pythondjangodjango-formsdjango-messages

How to write a Django message into your views code


I'm reading the documentation on how to display a message to the user with Django messages. It says that in order to add a message in your views to call:

from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')

I'm not sure where to put the second the second line, this is my view:

def sign_up(request):

    if request.method == "POST":
        form = IdForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
            ID = post.id_text
            return HttpResponse('Thank you')
        else:
            return HttpResponse('That text is invalid')
    else:
        form = IdForm()
    return render(request, 'checkin/base.html', {'form': form})

I want the message to appear and thank the user for signing up and display their input as well.


Solution

  • Bearing, in mind that it's customary to redirect to a success url on valid form submission, your code ought to look like this:

    def sign_up(request):
    
        if request.method == "POST":
            form = IdForm(request.POST)
            if form.is_valid():
                post = form.save()
                post.save()
                ID = post.id_text
                messages.add_message(request, messages.INFO, 'Hello world.')
                return HttpResponseRedirect('/thank-you-page/')
    
        else:
            form = IdForm()
        return render(request, 'checkin/base.html', {'form': form})
    

    note that this also results in the user being told why exactly his form is invalid (assuming that you have set up the template propertly). It's always good to say what the problem is rather than to say there is a problem.