如何在django中使用“email”作为“username”?

jtoj6r0c  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(160)

大家好,我是django的新手,我正在创建一个项目,我用表“tblusuarios”创建了一个数据库,并设法插入必要的数据,如姓名,姓氏,电子邮件,密码,然而,当我去登录时,我使用字段“mail”作为用户名,但到目前为止未能登录。你能给我什么建议吗?用户型号:

class TblUsuarios(AbstractBaseUser, models.Model):
    nombre = models.CharField(max_length=80)
    apellidos = models.CharField(max_length=80, blank=True, null=True)
    correo = models.CharField(max_length=80, unique=True)
    telefono = models.CharField(max_length=11, blank=True, null=True)
    password = models.CharField(max_length=80)
    foto = models.ImageField(upload_to='images/')
    tbl_roles = models.ForeignKey(TblRoles, models.DO_NOTHING, default=1)

    # object = CustomAccountManager()
    USERNAME_FIELD = 'correo' #le damos el username por defecto a la tabla
    REQUIRED_FIELDS=(['nombre'])
    class Meta:
        db_table = 'tbl_usuarios'

查看功能:

def login_user(request):
    if request.method == 'POST':
        correo = request.POST['email']
        password = request.POST['password']

        user = authenticate(request, username = correo, password = password)
        print(user)
        if user is not None:
            login(request, user)
            messages.info(request, 'Has ingresado correctamente a la aplicacion!!')
            return redirect('home')
        else:
            messages.error(request, 'Ha ocurrido un error a la hora de iniciar sesion!')
            return redirect('login')
    else:
        context = {}
        return render(request, 'users/login.html', context)

登录表单:

{% extends "layouts/layout.html" %} {% block content %}

{% if user.is_authenticated %}
    <h2>Ya estas logueado en nuestra aplicación</h2>
{% else %}

<section class="vh-100">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-6 text-black">
        <div
          class="d-flex align-items-center h-custom-2 px-5 ms-xl-4 mt-5 pt-5 pt-xl-0 mt-xl-n5"
        >
          <form style="width: 23rem" method="post" action="">
              {% csrf_token %}
            <h3 class="fw-normal mb-3 pb-3" style="letter-spacing: 1px">
              Log in
            </h3>

            <div class="form-outline mb-4">
              <input
                type="email"
                id="email"
                class="form-control form-control-lg"
                name="email"
              />
              <label class="form-label" for="email"
                >Correo</label
              >
            </div>

            <div class="form-outline mb-4">
              <input
                type="password"
                id="password"
                class="form-control form-control-lg"
                name="password"
              />
              <label class="form-label" for="password">Contraseña</label>
            </div>
            
            <div class="pt-1 mb-4">
                <input type="submit" value="Ingresar"  class="btn btn-info btn-lg btn-block">
            </div>

            <p class="small mb-5 pb-lg-2">
              <a class="text-muted" href="#!">Olvidaste tu contraseña?</a>
            </p>
            <p>
              No tienes una cuenta?
              <a href="/register/" class="link-info">Registrate acá</a>
            </p>
          </form>
        </div>
      </div>
      <div class="col-sm-6 px-0 d-none d-sm-block">
        <img
          src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/img3.webp"
          alt="Login image"
          class="w-100 vh-100"
          style="object-fit: cover; object-position: left"
        />
      </div>
    </div>
  </div>
</section>
{% endif %}
{% endblock content %}

因此,正如我所说的,视图函数中的变量“user”总是“none”。
我将“USERNAME_FIELD”变量添加到我的用户模型中,但是它没有起作用。

xzv2uavs

xzv2uavs1#

据我所知,你不应该同时继承AbstractBaseUsermodels.Model。参见文档中的工作示例:
代码示例:

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

class MyUser(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    ...
    USERNAME_FIELD = "identifier"

此外,在您的设置中,不要忘记精确您想要与AUTH_USER_MODEL一起使用的用户模型,请参考此处。
在您的settings.py中:

# ...
AUTH_USER_MODEL = "path.to.your.model.YourCustomUserModel"
# ...
mv1qrgav

mv1qrgav2#

我觉得这样更好。我这样做,但我不知道登录部分,因为我写的不同。请这样做,如果不行,请在这里告诉我。

from mymodel import TblUsuarios

def login_user(request):
    if request.method == 'POST':
        correo = request.POST.get['email']
        password = request.POST.get['password']
        if correo != '' and password != ''
            if TblUsuarios.objects.filter('email' = email).exists():            #If the email was in the database 
                TblUsuariosObject = TblUsuarios.objects.get('email' = email)    #Get Object with entered email
                if TblUsuariosObject.password == password:                      #check this email password == password in input
                    print(TblUsuariosObject.correo)
        # user = authenticate(request, username = correo, password = password)
        # print(user)
        # if user is not None:
                    login(request, user)
                    messages.info(request, 'Has ingresado correctamente a la aplicacion!!')
                    return redirect('home')
                else:
                    messages.error(request, 'Ha ocurrido un error a la hora de iniciar sesion!')
                    return redirect('login')
            else:
                messages.error(request, 'dont have this email in the Database')
                return redirect('login')
        else:
            messages.error(request, 'Null Inputs')
            return redirect('login')
    else:
        context = {}
        return render(request, 'users/login.html', context)

相关问题