从默认用户模型django更新字段

时间:2018-10-05 12:51:28

标签: django django-models django-users

我正在制作一个想要扩展默认用户模型的应用程序。我想自定义一些字段,例如为用户名添加一些限制。例如,用户名必须介于4到16个字符之间,并且只能包含小写字母,破折号和点。

我的问题是,如何在Django中更新这些字段?最佳做法是什么。我的模特在下面。

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

class CustomUserManager(UserManager):
    pass

class CustomUser(AbstractUser):
    objects = CustomUserManager()
    followers = models.ManyToManyField("self", related_name="following", symmetrical=False)

1 个答案:

答案 0 :(得分:0)

首先需要将文件form.py添加到您的项目中。然后将用户模型导入您的forms.py和models.py

from django.contrib.auth.models import User

如何扩展默认用户模型,您可以查看here

对于最大和最小符号,请使用Forms.py,例如:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
    username = forms.CharField(max_length=16, min_length=4, required=True, error_messages= {"username_exists": "Username already exists."})
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    email = forms.EmailField(max_length=100, required=True, error_messages= {"invalid": "Please, enter correct E-mail"})
    password1 = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
        widgets = {
        'password': forms.PasswordInput(),
    }

您可以在表单中引发任何错误消息,并在链接上方查找。