Сообщение об ошибке Login Failed на основе представлений Django

У меня есть проект, сделанный на django based view. Мне нужно показать сообщение об ошибке, когда пользователь вводит неправильный пароль, но на всех форумах, которые я видел до сих пор, есть предложение использовать 'Form'. Нет ли способа показать сообщение об ошибке в проекте, сделанном таким образом?

view.py:

def login(request):
if request.method == "GET":
    return render(request, 'users/login.html')
else:
    Email = request.POST.get('Email')
    Senha = request.POST.get('Senha')
    user = authenticate(username=Email, password=Senha)

    if user:
        loginDjango(request, user)
        return render(request, 'convite/cadastro_convite.html')
    else:
        return redirect('login')

html:

<div class="col-sm-12 col-md-7 login-dir">
                <h2 class="login-titulo">Faça seu login!</h2>
                <form class="login-form" action="{% url 'login'%}" method="POST"> {% csrf_token %}
                    <div class="form-group">
                        <input type="text" class="form-control" id="log-email" aria-describedby="emailHelp"
                            name="Email" placeholder="Email">
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control" id="log-senha" name="Senha" placeholder="Senha">
                    </div>
                    <button href="/Exemplo" type="submit" class="btn btn-primary login-btn_dir"><i
                            class="fa-solid fa-right-to-bracket"></i> Acessar</button>
                </form>
            </div>

модель:

 from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    NomeUsuario = models.TextField(blank=True)
    Endereco = models.TextField(blank=True)
    Celular = models.TextField(blank=True)
    Cidade = models.TextField(blank=True)
    Estado = models.TextField(blank=True)
    Cep = models.TextField(blank=True)
    Bairro = models.TextField(blank=True)

Хотя кажется, что использование django form более эффективно, да, есть способ сделать это из того, что у вас есть, просто добавив несколько строк кода.

Но вот моя первая рекомендация... Переименуйте ваш определенный метод login в loginDjango. Сделав это, вы сможете использовать метод django login без каких-либо потенциальных проблем.

Вы можете использовать приведенный ниже код для решения вашей проблемы:

from django.contrib.auth import login, get_user_model
from django.shortcuts import get_object_or_404


def loginDjango(request):
     context = {}         

     if request.method == "GET":
          return render(request, 'users/login.html', context)
     else:
          found = False

          Email = request.POST.get('Email')
          Senha = request.POST.get('Senha')
          
          # Try retrieving the user object from the get_user_model method
          user = get_object_or_404(get_user_model(), email=Email) # Assuming the email field is unique.

          # If a user object was returned then you can use the check_password method on the user object.
          if user:
               if user.check_password(Senha): # If the passwords matched
                    found = True
               else:
                    context['password_error'] = 'You have entered an incorrect password!'
          else:
               context['email_error'] = "Sorry, this email address doesn't exist!"
          
          # If the email exists and the password match then found is true...
          # Can use the authenticate within this if statement
          if found:
               # From the user object, using user.username -> username=user.username
               user = authenticate(username=user.username, password=Senha)
               
               # This if statement is not really necessary again but you can have it as a fail-safe
               if user:
                    # Use the django login method to log the user in.
                    login(request, user)
                    return render(request, 'convite/cadastro_convite.html')
          
          return render(request, 'users/login.html', context)

Затем в своем шаблоне вы можете проверить наличие ошибок, которые вы отправили через контекстный словарь.

<div class="form-group">
     <input type="text" class="form-control" id="log-email" aria-describedby="emailHelp" name="Email" placeholder="Email">
     {% if email_error %}<span>{{ email_error }}</span>{% endif %}
</div>

<div class="form-group">
     <input type="password" class="form-control" id="log-senha" name="Senha" placeholder="Senha">
     {% if password_error %}<span>{{ password_error }}</span>{% endif %}
</div>

Но я рекомендую вам прочитать doc и djano forms.

Более простой способ сделать это - использовать Django messages Framework

from django.contrib import messages

messages.info(request, '#message you want to show in the template')

Вы можете использовать For Loop или оператор If

Нравится:

{% for message in messages %}

 <p>{{message}}></p>

{% endfor %}
Вернуться на верх