用Django保存用户生成的密码

时间:2015-04-16 12:30:31

标签: python django

我正在尝试使用生成的密码和用户名保存用户,我遇到了一些麻烦。

我的view.py看起来像这样:

...
if request.method == "POST":

    u = get_username(request.POST.get('first_name', '').lower() + "." + request.POST.get('last_name', '').lower())
    p = User.objects.make_random_password(length = 6)

    form = PrincipalRegistrationForm(request.POST, request.FILES)

    if form.is_valid():

        ...

        new_user = form.save(uname = u, pword = p)

        return HttpResponseRedirect("/path/to/site")
...

和我的forms.py一样:

class PrincipalRegistrationForm(UserCreationForm ):

    first_name = forms.CharField(label = 'First name')
    last_name = forms.CharField(label = 'Last name')

    school = forms.ModelChoiceField(queryset = School.objects.all())
    profile_pic = forms.FileField(required=False)



    def save(self,commit = True, uname = "unkown", pword = "unknown"):   

        user = super(PrincipalRegistrationForm, self).save(commit = False)

        user.username = uname
        user.set_password = make_password(pword)

        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']


        if commit:
            user.save()
        return user

    def __init__(self, *args, **kwargs): 
            super(PrincipalRegistrationForm, self).__init__(*args, **kwargs) 
            self.fields.pop('username')
            self.fields.pop('password1')
            self.fields.pop('password2')

用户名由助手函数生成,由fname和lname组成,并且像代码一样发送到保存函数,它工作正常(如果我手动输入密码)。现在我希望密码生成并保存为用户名,但我遇到了问题。我收到了这些错误:

Exception Type: KeyError
Exception Value: u'password1'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py in save, line 121

感谢您提供任何帮助,我对如何编写代码或是否应该更改某些内容表示感谢。

回溯:

Environment:


Request Method: POST
Request URL: http://localhost:8000/siteadmin/add/principal

Django Version: 1.7.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app_accounts',
 'app_schools',
 'app_school_subjects')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:

    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
      111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/path/to/ednevnik/app_accounts/views.py" in add_principal
      80.             new_user = form.save(uname = u, pword = p)
    File "/path/to/ednevnik/app_accounts/forms.py" in save
      64.         user = super(PrincipalRegistrationForm, self).save(commit = False)
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py" in save
      121.         user.set_password(self.cleaned_data["password1"])

    Exception Type: KeyError at /siteadmin/add/principal
    Exception Value: u'password1'

解决:

def save(self, commit = True, uname = "unkown", pword = "unknown"):   
    # Adding this line solved my problem
    self.cleaned_data['password1'] = pword

    user = super(PrincipalRegistrationForm, self).save(commit = False)

    user.username = uname
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']

    if commit:
        user.save()
    return user

1 个答案:

答案 0 :(得分:0)

使用class Meta: exclude = ['somefield']和我的方式通过在进行正常保存之前更改表单实例来解决问题。