Django错误:__init __()获取关键字参数'max_length'的多个值 [英] Django Error: __init__() got multiple values for keyword argument 'max_length'

查看:376
本文介绍了Django错误:__init __()获取关键字参数'max_length'的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误。我不明白它的头尾。



__ init __()获得了关键字参数'max_length'的多个值



我从 django.contrib.auth添加了三个字段到 UserCreationForm 。表单
电子邮件名字姓氏,我想保存到我的User对象。
(名字和姓氏是否自动保存)。



这是我的表单我正在尝试加载。

  class MyRegistrationForm(UserCreationForm):
#define fields
email = forms .EmailField(required = True)
first_name = forms.CharField(_('first name'),max_length = 30,required = True)
last_name = forms.CharField(_('last name' ,max_length = 30,required = True)
helptext = {'username':*必须只包含字母和数字,
'email':*,
'password1' *必须包含大小写字母,数字特殊字符,
'password2':*输入与上述相同的密码进行验证

err_messages = {'invalid_username ':_(用户名必须只包含字母和数字),
'password_length':_(最小长度必须为8个字符),
'password_invalid':_包含特殊字符)}

def __init __(self,* args,** kwargs):
super(MyRegistrationForm,self).__ init __(* args,** kwargs)
用于['username','password1','password2','email']中的字段名:
self.fields [fieldname] .help_text = self.helptext [fieldname]
self.error_messages.update (self.err_messages)




class Meta:
model =用户
fields =('first_name','last_name' 'username','email','password1','password2')
#import pdb; pdb.set_trace()

def clean_username(self):
#由于User.username是唯一的,此检查是多余的,
#,但它设置了一个更好的错误消息ORM。见#13147。
username = self.cleaned_data [username]
如果不是re.match(r'^ \w + $',用户名):
raise forms.ValidationError(
self .error_messages ['invalid_username'],
code ='invalid_username',

return super(MyRegistrationForm,self).clean_username()


def clean_password2(self):
password1 = self.cleaned_data.get(password1)
如果len(password1)< 8:
raise forms.ValidationError(
self。 error_messages ['password_length'],
code ='password_length',

如果没有(re.search(r'[az]',password1)和
re.search (r'[AZ]',password1)和
re.search(r'[^ a-zA-Z\d\s:;]',password1)):
加注表单。 ValidationError(
self.error_messages ['password_invalid'],
code ='passwor d_invalid',

return super(MyRegistrationForm,self).clean_password2()

def clean_email(self):
email = self.cleaned_data [email ]
try:
user = User.objects.get(email = email)
print user.email
print user.username
raise forms.ValidationError(This电子邮件地址已存在。你是否忘记了密码?)
除了User.DoesNotExist:
返回电子邮件

def save(self,commit = True):
user = super(MyRegistrationForm ,self).save(commit = False)
user.email = self.cleaned_data [email]
如果提交:
user.save()
返回用户

我已经读过这个

  first_name = forms.CharField(label = _('first name') ,max_length = 30,required = True)

您也不需要保存第一个名字 last_name 明确地将被保存功能以上,除非你想要t o自己做一些清洁


I am getting this error. I do not understand the head and tail of it.

__init__() got multiple values for keyword argument 'max_length'.

I am adding three fields to UserCreationForm from django.contrib.auth.forms, which are email, first name and last name and I want to save them to my User object. (Does the first name and last name gets saved automatically).

Here is my form that I am trying to load.

class MyRegistrationForm(UserCreationForm):
    #define fields
    email=forms.EmailField(required=True)
    first_name = forms.CharField(_('first name'), max_length=30, required=True)
    last_name = forms.CharField(_('last name'), max_length=30, required=True)
    helptext={'username':"* must contain only alphabets and numbers",
              'email':"*",
              'password1':"*must contain alphabets in upper and lower case, numbers special char",
              'password2': "*Enter the same password as above, for verification"}

    err_messages={'invalid_username': _("username must include only letters and numbers"),
        'password_length': _("minimum length must be 8 characters"),
        'password_invalid':_("must include special character")}

    def __init__(self, *args, **kwargs):
        super(MyRegistrationForm, self).__init__(*args, **kwargs)
        for fieldname in ['username', 'password1', 'password2','email']:
            self.fields[fieldname].help_text = self.helptext[fieldname]
            self.error_messages.update(self.err_messages)




    class Meta:
        model=User
        fields=('first_name','last_name','username','email','password1','password2')
    #import pdb; pdb.set_trace()    

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        if not re.match(r'^\w+$',username):
            raise forms.ValidationError(
            self.error_messages['invalid_username'],
            code='invalid_username',
        )
        return super(MyRegistrationForm, self).clean_username()


    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        if len(password1)<8:
            raise forms.ValidationError(
            self.error_messages['password_length'],
            code='password_length',
        )
        if not (re.search(r'[a-z]', password1) and 
                re.search(r'[A-Z]', password1) and
                re.search(r'[^a-zA-Z\d\s:;]',password1)):
            raise forms.ValidationError(
            self.error_messages['password_invalid'],
            code='password_invalid',
        )
        return super(MyRegistrationForm, self).clean_password2()

    def clean_email(self):
            email = self.cleaned_data["email"]
            try:
                user = User.objects.get(email=email)
                print user.email
                print user.username
                raise forms.ValidationError("This email address already exists. Did you forget your password?")
            except User.DoesNotExist:
                return email

    def save(self, commit=True):
            user = super(MyRegistrationForm, self).save(commit=False)
            user.email=self.cleaned_data["email"]
            if commit:
                user.save()
            return user

I have read this article but it did not help in my situation.

解决方案

what Daniel suggested above should work.

first_name = forms.CharField(label=_('first name'), max_length=30, required=True)

you also dont need to save first name and last_name explicitly. It will be taken care by the save function you have above. unless you want to do some cleaning yourselves.

这篇关于Django错误:__init __()获取关键字参数'max_length'的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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