M
M
marataziat2018-02-27 20:00:23
Django
marataziat, 2018-02-27 20:00:23

How to display message in django?

I wrote this code in views:

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.contrib import messages
# Create you're views here.

def index(request):
    return render(request, 'eshkere.html')

@login_required
def loginedpage(request):
    return HttpResponse("LOL")

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        return redirect("/lolkek")
    else:
        # Return an 'invalid login' error message.
        messages.add_message(request, messages.INFO, 'Hello world.')
        return render(request, 'eshkere.html')

YES, shit but it's purely for practice. Here is eshkere.html:
<form action="/j" method="POST">
    {% csrf_token %}
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Submit">
    {% if messages %}
        {{ messages }}
    {% endif %}
</form>

I have a normal form on the page, but with a message when necessary:
5a958e75600c1638644034.png
​​In settings.py:
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
INSTALLED_APPS = [
    'kek',
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-27
@marataziat

{% for message in messages %}
    {{ message }}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question