LinkedRom
LinkedRom

Reputation: 175

How to display error message in Django template after HttpRedirect from another view?

I'm creating a simple CRUD application without using the admin page of Django. I only have one template, index.html that displays all the list of student information. I have two views below, one is for displaying only when the user visited the index page. The other view is executed when a user in the index page clicks a submit button for registering a new student (via POST) then redirects to the index view again. I want to display an error message if the student already exists in the database (by using student number). My problem is how can I pass the error message in the index.html template after the HttpRedirect. Or am I doing it the wrong way?

def index(request):

    studentList = Student.objects.all()

    return render(request, "crud/index.html", {"student_list": studentList})


def addStudent(request):

    data = request.POST

    # print(data)

    if data:

        try:
            newStudent = Student.objects.get(student_number=data['student_number'])

            return HttpResponseRedirect(reverse("crud:index"))

        except Student.DoesNotExist:
            newStudent = Student(student_number=data['student_number'],
                                 first_name=data['first_name'],
                                 last_name=data['last_name'],
                                 age=data['age'],
                                 sex=data['sex'],
                                 email=data['email']
                                 )
            newStudent.save()

    return HttpResponseRedirect(reverse("crud:index"))

Upvotes: 1

Views: 6532

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16032

You should use .get_or_create for this:

from django.core.exceptions import SuspiciousOperation

def addStudent(request):
    data = request.POST
    student, created = Student.objects.get_or_create(
        student_number=data['student_number'],
        first_name=data['first_name'],
        last_name=data['last_name'],
        age=data['age'],
        sex=data['sex'],
        email=data['email']
        )

    if created:
        return HttpResponseRedirect(reverse("crud:index"))

    else:
        raise SuspiciousOperation("student with id {} already exists!".format(data['student_number']))

Update

If you want to continue the redirect, and still send an alert to the user, you should use Django's built-in messages middleware.

Here is an example:

from django.contrib import messages

def addStudent(request):
    ...

    if not created:    
        messages.warning(request, 'Student with ID {} already exists!'.format(data['student_number']))

    return HttpResponseRedirect(reverse("crud:index"))

Now on your index.html, you need to check if any messages exist, and if they do, display them:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

If you want to customize how the message look and behave, see the docs for more details.

Upvotes: 2

Related Questions