以Django形式设置隐藏字段的值 [英] Setting value of a hidden field in Django form

查看:27
本文介绍了以Django形式设置隐藏字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using django-registration to manage my registrations. I'm trying to force my username and email to be the same in a Django application and I am trying to do it via the registration form as follows:

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 设置为 username .但我只是收到错误(隐藏字段电子邮件),此字段为必填字段

The idea is that if passwords match and the username is valid then I set the email to the username. But I just get the error (Hidden field email) This field is required

我应该如何设置.

推荐答案

因此,您可以按照注释中的说明进行操作,但是可以直接从字段定义中进行操作:

So for your answer you can do as you said in comment, but directly from the field definition :

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

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

Or just declare a form without an email field (so in your example : username, password1 and password2) and treat the username / email part in the form's save method :

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

您不必隐藏带有虚拟值的字段,我认为它是更干净"的.

There you don't have to hide a field with a dummy value, which i think is "cleaner".

这篇关于以Django形式设置隐藏字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆