Django Error: __init__() got multiple values for keyword argument 'max_length'

╄→尐↘猪︶ㄣ 提交于 2019-12-24 13:57:08

问题


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.


回答1:


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.




回答2:


Form fields are not model fields: they don't take a positional parameter as a verbose name. You need to specify it as the label kwarg:

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


来源:https://stackoverflow.com/questions/22543037/django-error-init-got-multiple-values-for-keyword-argument-max-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!