Having problems with message tags

77 Views Asked by At

I am trying to create dynamic messages depending on user input but no alert button even appears. However when I get rid of {% for message in messages%} an empty alert button appears.

views.py:

from django.shortcuts import render, redirect

from django.contrib.auth.models import User 
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout


def signup(request):

    if request.method == "POST":
        username = request.POST.get('username')
        email = request.POST.get('email')
        pass1 = request.POST.get('pass1')
        pass2 = request.POST.get('pass2')
        if pass1 != pass2:
            messages.info(request, "Password is not matching")
            return redirect('/authapp/signup/')

        try:
            if User.odjects.get(username=get_email):
                messages.warning(request, 'User with email already exist')
                return redirect('/authapp/signup/')
        
        except Exception as identifier:
            pass


        myuser = User.objects.create_user(username, email, pass1)
        myuser.save()

        messages.success(request, "Your Account has been successfully created, Login")
        return redirect('/authapp/signin/')

    return render(request, 'authapp/signup.html')

signup.html

{% for message in messages  %}   
  <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert">
     <strong> {{message}} </strong> 
     <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>   
  </div>            
{% endfor %}

settings.py

MESSAGE_TAGS = {
    messages.ERROR:'alert-info'
}
1

There are 1 best solutions below

0
Ahtisham On
MESSAGE_TAGS = {
    messages.ERROR:'alert-info'
}

You have changed the default settings of message tags from error to alert-info which will translate on the template to alert alert-alert-info class and there is no such class with that name in bootstrap. Replace alert-info to danger in settings and it will work.

You can also simlify and optimize the part where you have a check for duplicate email by removing try except and use exists like this:

if User.odjects.filter(username=email).exists():
   messages.warning(request, 'User with email already exist')
   return redirect('/authapp/signup/')