代码之家  ›  专栏  ›  技术社区  ›  HenryM

Django格式的隐藏字段的设置值

  •  1
  • HenryM  · 技术社区  · 6 年前

    django-registration 管理我的注册。我试图在Django应用程序中强制使用相同的用户名和电子邮件,并尝试通过注册表执行以下操作:

    class NoUsernameRegistrationForm(RegistrationForm):
        """
        Form for registering a new user account.
    
        Requires the password to be entered twice to catch typos.
    
        Subclasses should feel free to add any additional validation they
        need, but should avoid defining a ``save()`` method -- the actual
        saving of collected user data is delegated to the active
        registration backend.
    
        """
        username = forms.CharField(
            widget=forms.EmailInput(attrs=dict(attrs_dict, maxlength=75)),
            label=_("Email address"))
        password1 = forms.CharField(
            widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
            label=_("Password"))
        password2 = forms.CharField(
            widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
            label=_("Password (again)"))
        email = forms.EmailField(
            widget=forms.HiddenInput(),
            required = False)
    
    
        def clean(self):
            """
            Verify that the values entered into the two password fields
            match. Note that an error here will end up in
            ``non_field_errors()`` because it doesn't apply to a single
            field.
    
            """
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                    raise forms.ValidationError(_("The two password fields didn't match."))
    
            """
            Validate that the email address is not already in use.
    
            """
            try:
                user = User.objects.get(username__iexact=self.cleaned_data['username'])
                raise forms.ValidationError(_("A user with that email address already exists."))
            except User.DoesNotExist:
                self.cleaned_data['email'] = self.cleaned_data['username']
                self.cleaned_data['username']
    
    
            return self.cleaned_data
    

    username 是有效的然后我设置 email 用户名 . 但我只是得到了一个错误 (Hidden field email) This field is required

    我该怎么设置这个。

    1 回复  |  直到 6 年前
        1
  •  5
  •   Bestasttung    6 年前

    因此,对于你的答案,你可以按照你在评论中说的做,但直接从字段定义:

    email = forms.EmailField(
        widget=forms.HiddenInput(),
        required = False,
        initial="dummy@freestuff.com"
    )
    

    或者只声明一个没有email字段的表单(在您的示例中: username , password1 password2 )并在表单的保存方法中处理用户名/电子邮件部分:

    def save(self, commit=True):
        user = super().save(commit=False) # here the object is not commited in db
        user.email = self.cleanned_data['username']
        user.save()
        return user
    

    在这里,您不必隐藏一个带有伪值的字段,我认为它“更干净”。