如何自定义用户名验证

时间:2017-12-30 03:00:53

标签: python django

我正在尝试为django.contrib.auth用户模型自定义用户名验证。它显示Usernames may contain alphanumeric, _, @, +, . and - characters.,但我想这样做,如果用户使用@, ., -, +创建了用户名,它将无效。如何覆盖此验证,以便在用户创建用户名时使用我的自定义验证而不是原始UnicodeUsernameValidator

我正在使用自己的自定义用户模型,但我继承自AbstractBaseUser是否有一种简单的方法来添加我的用户名验证?

3 个答案:

答案 0 :(得分:1)

您可以在模型类上设置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()

答案 1 :(得分:0)

@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')

答案 2 :(得分:0)

假设您正在使用 users 应用程序,并且自定义用户模型的名称为CustomUser,位于 users / models.py 中。如果您不想在用户名中使用@, ., -, +,请创建一个 forms.py ,它看起来像这样:

users / 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 应该如下所示:

users / 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 和模板。

users / 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.'
...

users / templates / signup.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脆皮表格或用户名/电子邮件中的大小写不敏感,或者避免为有时键入email@gmail.comemail@googlemail.com的用户重复。两者都是同一封电子邮件。如果您不包括检查,那么您的数据库中将有重复的用户。