0

i have a login django app where i am trying to inform user in if they have wrong credentials or if they are successfully login.

the problem is that i used the message framework in django but it did not showed up in the template.

views.py

from django.contrib import messages


def login_request(request):
    if request.method == "POST":
        username = request.POST['lognName']
        password = request.POST['lognCode']
        user = authenticate(username = username,password = password)
        if user is not None:
            login(request,user)
            messages.info(request,f"You are now logged in as {username}")
            return redirect("main")
        else:
            messages.error(request,"invalid username or password")

    return render(request,'login.html')

login.html

{% if messages %}
    {% for message in messages %}
        <script>M.toast({html:"{{message}}",classes:'blue rounded',displaylength:2000});</script>
    {% endfor %}
{% endif %}

even if i tried to used outside the if statement the toast doesn't work

Django Dg
  • 97
  • 4
  • 19

1 Answers1

0

Try to set the script inside $(document).ready(function($) { /* foreach message M.toast(...) */ });

I will personally do it in a separate js file.

If you want to access to the messages object from js check out this link: Django Template Variables and Javascript

Hagyn
  • 922
  • 7
  • 14