Mariana Gomez-Kusnecov
Mariana Gomez-Kusnecov

Reputation: 245

Displaying a message as a popup/alert in Django?

I have a form that, upon submission it just redirects to itself again. I'm trying to display a message that says "You have entered (work_area)." Currently, I only got the displaying part without the variable in it, but it shows within the html after the user submits it. I would like it to be a popup or alert message that the user can close after they see it, but I don't understand how this would work in Django.

views.py

class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm
    #success_message = "You have logged into %(work_area)s"

    def form_valid(self, form):
        emp_num = form.cleaned_data['employee_number']
        area = form.cleaned_data['work_area']
        station = form.cleaned_data['station_number']

        if 'enter_area' in self.request.POST:
            form.save()
            EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(station_number=station)).update(time_in=datetime.now())

            messages.info(self.request, "You have entered")
            return HttpResponseRedirect(self.request.path_info)

enter_exit_area.html

{% extends "base.html" %}

{% block main %}
    <form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
        {% csrf_token %}

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

        <div>
            <div>
                <label>Employee</label>
                {{ form.employee_number }}
            </div>

            <div>
                <label>Work Area</label>
                {{ form.work_area }}
            </div>
            <div>
                <label>Station</label>
                {{ form.station_number }}
            </div>
        </div>

        <div>
            <div>
                <button type="submit" name="enter_area" value="Enter">Enter Area</button>

            </div>
        </div>
    </form>

{% endblock main %}

And it displays like this:

Edit:

enter image description here

Upvotes: 4

Views: 15532

Answers (2)

wolfrevo
wolfrevo

Reputation: 1

Django has built-in functions for that which is messages.

messages.success(self.request,"message sent")

In your HTML, make sure to create a message class.

{% if message.tags %} class="{{message.tags}}"{% endif %}

Upvotes: 0

Pedram
Pedram

Reputation: 3920

This is more a javascript question but anyways, this is how I handle this (if you are using bootstrap):

1) Create a message.html file with the following content:

{% for message in messages %}
  <div class="toast notification bg-{% if message.tags == 'error' %}danger{% else %}{{message.tags}}{% endif %}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
    <div class="toast-header">
      <strong class="mr-auto">
        {% if message.tags == 'error' %}
          <i class="fas fa-times mr-2"></i>
        {% elif message.tags == 'warning' %}
          <i class="fas fa-exclamation mr-2"></i>
        {% elif message.tags == 'info' %}
          <i class="fas fa-info mr-2"></i>
        {% elif message.tags == 'success' %}
          <i class="fas fa-check mr-2"></i>
        {% endif %}
        {{message.tags|capfirst}}
      </strong>
      <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="toast-body">
      {{message|safe}}
    </div>
  </div>
{% endfor %}

2) Change your base.html and add:

...
{% include 'message.html' %}
...


<!-- and at the end:-->
<script src="{% static 'js/jquery-3.4.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% if messages %}
  <script>
      {% for message in messages %}
          $(document).ready(function () {
              $('.toast').toast('show');
          });
      {% endfor %}
  </script>
{% endif %}

Also, don't forget to include bootstrap.

This way you can use django messages on all of your templates, without explicitly change them.

Edit

You also need this custom css class in order for your notification to show on top right of the page:

.notification{
    position: absolute;
    top: 5rem;
    right: 1rem;
}

Upvotes: 16

Related Questions