如何在Django中将字段”email”用作”username”?

huangapple go评论71阅读模式
英文:

How to use the field "email" as "username" in django?

问题

In your view function, it appears that you are using the field "email" for authentication, but you've defined "correo" as the email field in your user model. Make sure you are using the correct field name when trying to authenticate the user.

你的视图函数中似乎在进行身份验证时使用了字段 "email",但在用户模型中定义了 "correo" 作为电子邮件字段。确保在尝试验证用户时使用正确的字段名称。

英文:

Hello everyone I am new to django and I am creating a project where I created a database with a table "tblusuarios" and managed to insert the necessary data such as name, surname, email, password, however, when I go to make the login I am using the field "mail" as username, but so far fails to make the login. Any advice you can offer me?
User model:

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'

View function:

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)

Login form:

{% 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 %}

So as I say, always the variable "user" in the view function comes as "none".

I added the "USERNAME_FIELD" variable to my user model, however it did not work.

答案1

得分: 1

根据我所知,你不应该同时继承自 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"
# ...
英文:

As far as I know you should not inherit both from AbstractBaseUser and models.Model. See working example from docs :

Code sample :

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"

Also in your settings do not forget to precise the user model you want to use with the AUTH_USER_MODEL, reference here.

In your settings.py :

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

答案2

得分: 0

我认为这样做更好。我是这样做的,但是关于登录部分我不清楚,因为我以不同的方式编写它。请按照这种方式操作,如果不起作用,请在此通知我。

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():  # 如果邮箱在数据库中
                TblUsuariosObject = TblUsuarios.objects.get(email=email)  # 获取输入的邮箱对应的对象
                if TblUsuariosObject.password == password:  # 检查此邮箱的密码是否与输入的密码匹配
                    print(TblUsuariosObject.correo)
                    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, '数据库中没有此邮箱')
                return redirect('login')
        else:
            messages.error(request, '空输入')
            return redirect('login')
    else:
        context = {}
        return render(request, 'users/login.html', context)
英文:

I think it's better this way. I do it like this, but I don't know about the login part because I write it differently. Please do it this way, and if it doesn't work, let me know here.

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)


huangapple
  • 本文由 发表于 2023年6月13日 07:46:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定