【问题标题】:Django UserCreationForm custom fieldsDjango UserCreationForm 自定义字段
【发布时间】:2018-06-11 11:34:08
【问题描述】:

我正在尝试为用户注册创建表单并添加一些自定义字段。为此,我将 UserCretionForm 子类化并添加了字段,如 django 文档中所示。然后我基于这个表单创建了基于函数的视图和模板。现在,我可以成功创建用户,并且该用户已按预期添加到管理面板。问题是,我无法为此表单的字段添加类和样式。除用户名字段外,小部件不起作用。我在这里添加我的脚本以更准确地说明我的问题:

forms.py

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


class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=32, help_text='First name')
    last_name = forms.CharField(max_length=32, help_text='Last name')
    email = forms.EmailField(max_length=64, help_text='Enter a valid email address')

    class Meta(UserCreationForm.Meta):
        model = User
        # I've tried both of these 'fields' declaration, result is the same
        # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
        fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)

        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}),
            'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}),
            'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}),
            'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}),
        }

views.py

from django.contrib.auth import login, authenticate
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirect

from .forms import SignUpForm, SignInForm


def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render

“forms.py”中的小部件除了“用户名”字段外不工作。换句话说,在 Web 浏览器中,“用户名”输入显示为“class='form-control'”和“placeholder='Username'”,但其他字段没有我预期的类和占位符属性。可能是什么原因?

【问题讨论】:

    标签: python django authentication forms-authentication user-registration


    【解决方案1】:

    您无需在小部件下定义字段。在类级别将它们定义为静态。

    class SignUpForm(UserCreationForm):
        username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))
        first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name')
        last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name')
        email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address')
        password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
        password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}))
    
        class Meta(UserCreationForm.Meta):
            model = User
            # I've tried both of these 'fields' declaration, result is the same
            # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
            fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
    

    【讨论】:

    • 谢谢!它现在可以工作了,但是您应该在每个小部件参数之前添加 'widget='。
    【解决方案2】:

    只需在@Chirdeep 答案上添加注释,如果您尝试呈现表单,您将丢失 field.help_text 的密码。

    为了解决这个问题,我们可以重写如下表格 请注意从django.contrib.auth导入password_validation

    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth import password_validation
    from django.contrib.auth.models import User
    from django.utils.translation import gettext_lazy as _
    from django.contrib.auth.validators import UnicodeUsernameValidator
    
    username_validator = UnicodeUsernameValidator()
    
    class SignUpForm(UserCreationForm):
        first_name = forms.CharField(max_length=12, min_length=4, required=True, help_text='Required: First Name',
                                    widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}))
        last_name = forms.CharField(max_length=12, min_length=4, required=True, help_text='Required: Last Name',
                                   widget=(forms.TextInput(attrs={'class': 'form-control'})))
        email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.',
                                 widget=(forms.TextInput(attrs={'class': 'form-control'})))
        password1 = forms.CharField(label=_('Password'),
                                    widget=(forms.PasswordInput(attrs={'class': 'form-control'})),
                                    help_text=password_validation.password_validators_help_text_html())
        password2 = forms.CharField(label=_('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}),
                                    help_text=_('Just Enter the same password, for confirmation'))
        username = forms.CharField(
            label=_('Username'),
            max_length=150,
            help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
            validators=[username_validator],
            error_messages={'unique': _("A user with that username already exists.")},
            widget=forms.TextInput(attrs={'class': 'form-control'})
        )
    
        class Meta:
            model = User
            fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
    

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 2014-03-01
      • 2021-05-07
      • 2020-11-26
      • 2013-05-09
      • 1970-01-01
      • 2020-08-25
      • 2021-01-16
      相关资源
      最近更新 更多