Django密码不匹配获取属性

时间:2016-02-20 18:16:12

标签: python django

我在注册时遇到了这个问题。

我在forms.py注册了

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    confirm_password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ('username', 'email')

    def clean(self):
       # Check that the two password entries match
       password = self.cleaned_data.get("password")
       conf_password = self.cleaned_data.get("confirm_password")
       if conf_password and password and conf_password != password:
           raise forms.ValidationError("Passwords don't match")
       return password

当我尝试从我的本地主机注册时,会发生这种情况:

AttributeError at /signup/
'str' object has no attribute 'get'
Request Method: POST
Request URL:    http://127.0.0.1:8000/signup/
Django Version: 1.9.1
Exception Type: AttributeError
Exception Value:    
'str' object has no attribute 'get'
Exception Location: C:\Users\Hai\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\models.py in _get_validation_exclusions, line 337
Python Executable:  C:\Users\Hai\AppData\Local\Programs\Python\Python35-32\python.exe
Python Version: 3.5.0
Python Path:    
['C:\\Users\\Hai\\OneDrive\\WebSoftware\\p3\\wsd_game',
 'C:\\Users\\Hai\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip',
 'C:\\Users\\Hai\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs',
 'C:\\Users\\Hai\\AppData\\Local\\Programs\\Python\\Python35-32\\lib',
 'C:\\Users\\Hai\\AppData\\Local\\Programs\\Python\\Python35-32',
 'C:\\Users\\Hai\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages']
Server time:    Sat, 20 Feb 2016 20:09:17 +0200

如果我评论def clean(自我)但是我需要密码来匹配彼此,这个问题就消失了。

除此注册表外,其他所有内容均按计划进行。当我完成表单并按下寄存器后,出现'get'属性错误。

查看

def register(request):
# Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

            # Invalid form or forms - mistakes or something else?
            # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print (user_form.errors, profile_form.errors)

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render_to_response(
            'registration/sign_up.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)

模型:

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User)

    # The additional attributes we wish to include.
    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_images', blank=True)
    CHOICES = (('pl', 'Player'),('dv', 'Developer'),)
    user_type = models.CharField(max_length=2,choices=CHOICES,default='pl')


    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

1 个答案:

答案 0 :(得分:2)

在清理功能结束时,您将返回密码本身,模型视图无法使用get访问它(因为它是一个字符串)。只需添加return self.cleaned_data而不是return password,一切都应该正常。