django 如何自定义用户名验证

mrphzbgm  于 2023-03-20  发布在  Go
关注(0)|答案(3)|浏览(150)

我正在尝试为django.contrib.auth用户模型自定义用户名验证。它显示为Usernames may contain alphanumeric, _, @, +, . and - characters.,但我希望使其在用户使用@, ., -, +创建用户名时无效。如何覆盖此验证,以便在用户创建用户名时使用我的自定义验证而不是原始UnicodeUsernameValidator
我正在使用我自己的自定义用户模型,但我是从AbstractBaseUser继承的。是否有一种简单的方法来添加我的用户名验证?

ct2axkht

ct2axkht1#

有一个username_validator属性可以在模型类上设置:
指向用于验证用户名的验证程序示例。默认值为validators.UnicodeUsernameValidator
要更改默认的用户名验证器,您可以将User模型子类化,并将此属性设置为不同的验证器示例。例如,要使用ASCII用户名:

from django.contrib.auth.models import User
from django.contrib.auth.validators import ASCIIUsernameValidator

class CustomUser(User):
    username_validator = ASCIIUsernameValidator()
odopli94

odopli942#

假设您正在使用users应用,自定义用户模型的名称为CustomUser,位于users/models.py中。如果您不希望在用户名中使用@, ., -, +,请创建一个forms.py,如下所示:

用户/forms.py

from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'first_name', 'last_name', 'email')

    def clean(self):
        cleaned_data = super(CustomUserCreationForm, self).clean()
        username = cleaned_data.get('username')
        if ('@', '.', '-', '+') in username:
            self.add_error('username', 'Symbols @/./-/+ are not allowed in username.')
        return cleaned_data

# same for UserChangeForm
class CustomUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = CustomUser
        fields = ('username', 'first_name', 'last_name')
        # Removed email field. Anyone won't want to change email after registering. Go as you like.

    def clean(self):
        cleaned_data = super(CustomUserChangeForm, self).clean()
        username = cleaned_data.get('username')
        if ('@', '.', '-', '+') in username:
            self.add_error('username', 'Symbols @/./-/+ are not allowed in username.')
        return cleaned_data

如果有人尝试在用户名中使用@, ., -, +注册,将显示您的自定义错误消息。
要修改Django的默认描述Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.,你的models.py应该如下所示:

用户/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.validators import UnicodeUsernameValidator

User = get_user_model

class CustomUser(AbstractUser):
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        "Username",
        max_length = 150,
        unique = True,
        help_text = ("Required. 150 characters or fewer. Letters, and digits only."),
        # customize the above string as you want
        validators = [username_validator],
        error_messages = {
            'unique': ("A user with that username already exists."),
        },
    )
    email = models.EmailField(max_length=254, blank=False, unique = True)
    first_name = models.CharField(max_length = 30, blank = False)
    last_name = models.CharField(max_length = 50, blank = False)

同时也不要忘记检查你的views.py和你的模板。

用户/views.py

from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
...

# Create your views here.
class SignUpView(SuccessMessageMixin, CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
    success_message = 'Account was created successfully! Now Log In using your details.'
...

用户/模板/注册.html

...

{% block content %}
    <h2>Sign Up</h2>    
    <div>
        <form action="" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <button class="" type="submit">Sign Up</button>
        </form>
    </div>
{% endblock content %}
...

这是你必须使用的最小HTML。然后一切都将按照你想要的方式工作。
您可以添加更多的自定义设置(例如添加Django cripy表单,或用户名/电子邮件不区分大小写,或避免重复输入email@gmail.comemail@googlemail.com的用户。这两个电子邮件是相同的。如果您不包含检查,那么您的数据库中会有重复的用户。

wgx48brx

wgx48brx3#

@Bytes这是肮脏的伎俩,但工作:-

def loginup(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']

        #Manual code to Check whether username is valid or not
        try:
         myuser = User.objects.get(username=username)
        except:
            myuser = False

        if myuser == False:
            mypass = False
        else:
            mypass = myuser.check_password(password)
        user = auth.authenticate(username=username, password=password)
        if myuser != False:
            if user is not None:
                auth.login(request, user)
                messages.success(request, "You have Successfully Logged in")
                return render(request, 'index.html')
            else:
                messages.error(request, "Invalid Password")
                return render(request, 'index.html')
        else:
            messages.error(request, "Invalid Username")
            return render(request, 'index.html')
    return render(request, 'index.html')

相关问题