首先,如何为min_length
设置username
?
ChachaUser._meta.get_field('username').min_length = 2
无效。
其次,如何为placeholder
和password1
放置password2
?
forms.PasswordInput(attrs={'placeholder' : "6자리 이상"}),
无效。
这是我自定义的User
模型和UserCreationForm
。
models.py
from django.core.validators import RegexValidator
from django.contrib.auth.models import AbstractUser
from django.db import models
GENDER_CHOICES = (
('M', '남'),
('F', '여'),
)
phone_regex = RegexValidator(
regex=r'^\d{11}$',
message=" '-' 없이 입력해주세요",
)
username_regex = RegexValidator(
regex=r'^[0-9a-zA-Z]*$',
message='아이디는 영어와 숫자로만 구성되어야 합니다.'
)
class ChachaUser(AbstractUser):
birth = models.DateField("생년월일")
name = models.CharField(
"이 름",
max_length=4
)
gender = models.CharField(
"성 별",
max_length=1,
choices=GENDER_CHOICES,
default='M'
)
phone_number = models.CharField(
"핸드폰",
validators=[phone_regex],
max_length=11
)
job = models.CharField(
"직 업",
max_length=20,
)
# python manage.py createsuperuser 할 때 나오는 항목
REQUIRED_FIELDS = [
'birth',
'name',
'gender',
'phone_number',
'job',
'email'
]
ChachaUser._meta.get_field('username').verbose_name = '아이디'
ChachaUser._meta.get_field('username').validators = [username_regex]
ChachaUser._meta.get_field('username').max_length = 20
ChachaUser._meta.get_field('username').min_length = 2
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
class MyUserCreationForm(UserCreationForm):
birth = forms.DateField(
label="생년월일",
widget=forms.SelectDateWidget(
years=range(1970, 2015)
),
)
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = UserCreationForm.Meta.fields + (
'name',
'gender',
'birth',
'phone_number',
'job',
)
exclude = ('email', )
widgets = {
'username' : forms.TextInput(
attrs={'placeholder': '알파벳, 숫자만 가능(20자 이내)'}
),
'phone_number' : forms.TextInput(
attrs={'placeholder' : "ex) 01012341234"}
),
'job' : forms.TextInput(
attrs={'placeholder' : "ex) 한국대 철학과, 선생님 등(20자 이내)"}
),
'password1' : forms.PasswordInput(
attrs={'placeholder' : "6자리 이상"}
),
'password2' : forms.PasswordInput(
attrs={'placeholder' : "6자리 이상"}
),
}
答案 0 :(得分:0)
对于第一个问题:
from django.core import validators
class ChachaUser(AbstractUser):
..................
AbstractUser._meta.get_field('username').validators=[validators.MinLengthValidator(2)]
对于第二个问题,您无法更改password1
中的Meta.widgets
,因为它不是模型字段。您可以改为使用__init__
方法覆盖小部件。
答案 1 :(得分:0)
如果有人在寻找如何“替换__init__
方法中的小部件”。正如Anna Vracheva对OP第二个问题的回答所提到的那样。这里有一个小代码片段可以提供帮助:
class MyUserCreationForm(UserCreationForm):
def __init__(self, *args, **kargs):
super(MyUserCreationForm, self).__init__(*args, **kargs)
self.fields['password1'].widget = PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control'})
self.fields['password2'].widget = PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'form-control'})
class Meta:
model = User
有关详细信息,请查看此question。