0

I am trying to use both django messages and bootstrap together.

I also checked this question;

django messages not showing

However, I already applied what is written there.

My settings.py;

from django.contrib.messages import constants as messages

# some other codes #

MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}

# some other codes #

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
.
.
# other apps
]

# some other codes #

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_pdb.middleware.PdbMiddleware',
]

# some other codes #

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.template.context_processors.media',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

My products/views.py;

# some other imports #

from django.contrib import messages

# some other codes # 

def oxford(request):
    search_result = {}
    if 'word' in request.GET:
        form = DictionaryForm(request.GET)
        if form.is_valid():
            search_result = form.search()
            messages.success(request, 'Your query is successful!')
    else:
        form = DictionaryForm()
        messages.warning(request, 'Please correct the error.')
    return render(request, 'products/oxford.html', {'form': form, 'search_result': search_result})

My products/urls.py;

# some imports here #

app_name = 'products'
urlpatterns = [
    path('', views.IndexView.as_view(), name='base'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('oxford/', views.oxford, name='oxford'),
    # some other urls here #
]

myproject/templates/dashboard.html (not in the app folder);

{% load static %}

<html lang="en">
    <head>
        # some code here #
    </head>
    <body>
        # some code here #
        {% block main %}
        {% endblock main %}
    </body>
</html>

products/templates/products/base_products.html;

{% extends 'dashboard.html' %}

{% block page_main_title %}
{% endblock page_main_title %}

{% block list_html_app_css %}
{% endblock list_html_app_css %}

{% block main %}
  {% block show_message %}
  {% endblock show_message %}
{% endblock main %}

{% block graph %}
{% endblock graph %}

products/templates/products/oxford.html;

{% extends 'products/base_products.html' %}
{% load static %}

{% block main %}
  <main>
    <div>
      # some code here #
    </div>

    <div class="border-bottom">
      {% block get_oxford %}

      <h2>Oxford Dictionary</h2>

      <form method="get">
      {{ form.as_p }}
        <button type="submit">search</button>
      </form>

      {% if search_result %}
        <hr>
        {% if search_result.success %}
          {% for result in search_result.results %}
            <h3>{{ result.word }}</h3>
              {% for lexicalentry in result.lexicalEntries %}
                 <h4>{{ lexicalentry.lexicalCategory }}</h4>
                 <ul>
                 {% for entry in lexicalentry.entries %}
                    {% for sense in entry.senses %}
                       {% for definition in sense.definitions %}
                          <li>{{ definition }}</li>
                       {% endfor %}
                    {% endfor %}
                 {% endfor %}
                 </ul>
              {% endfor %}
          {% endfor %}
       {% else %}
         <p><em>{{ search_result.message }}</em></p>
       {% endif %}
     {% endif %}

     {% endblock get_oxford %}
   </div>
   <div class="container">
    {% block show_message %}
      {% include 'products/messages.html' %}
    {% endblock show_message %}
   </div>
 </main>

{% endblock main %}

products/templates/products/messages.html;

{% if messages %}
  {% for message in messages %}
    <div class="alert 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 %}
{% endif %}

I cannot find what I am missing here. Thank you for your time and answers.

Hektor
  • 105
  • 3
  • 14

1 Answers1

0

add an other message if form is not valid for try :

# some other imports #

from django.contrib import messages

    # some other codes # 

def oxford(request):
    search_result = {}
    if 'word' in request.GET:
        form = DictionaryForm(request.GET)
        if form.is_valid():
            search_result = form.search()
            messages.success(request, 'Your query is successful!')
        else:
            messages.warning(request, 'form is not valid.')
    else:
        form = DictionaryForm()
        messages.warning(request, 'Please correct the error.')
    return render(request, 'products/oxford.html', {'form': form, 'search_result': search_result})
oz grow
  • 55
  • 10
  • and made juste 'messages.add_message(request, messages.INFO, 'ok"')' on top of your view, – oz grow Aug 11 '18 at 09:58
  • If I write it before view function, then I am getting `NameError: name 'request' is not defined` error which is normal I think. I tried to write this just before `search_result = {}` but there is still no change. – Hektor Aug 11 '18 at 14:06
  • 1
    `{% if messages %}
      {% for message in messages %}
    • {{ message|capfirst }}
    • {% endfor %}
    {% endif %}` put in on your template
    – oz grow Aug 11 '18 at 14:25
  • I changed my messages.html code with yours, then it worked that I could see the messages however why I cannot apply bootstrap alerts' features as it is shown here: https://v4-alpha.getbootstrap.com/components/alerts/ ? – Hektor Aug 11 '18 at 15:08
  • you can maybe encapse the code with your div ` – oz grow Aug 11 '18 at 15:27
  • or juste erase actual ul class or li class for try, do you need to made some test, the first step is ok now just trying to do add your bootstrap and control if the message is visible after all change – oz grow Aug 11 '18 at 15:30
  • why ` – oz grow Aug 11 '18 at 15:49
  • No I cannot get the result if I add `div` part. I think `alert-dismissible` part lets you close the alert after it appears. I also tried to change `
      ` and `
    • ` tags but no chance.
    – Hektor Aug 11 '18 at 16:05