Django AttributeError:'User'对象没有属性'set_password'但是用户没有覆盖

时间:2016-12-26 15:05:12

标签: python django python-2.7

我有以下错误:

AttributeError: 'User' object has no attribute 'set_password'

问题是我没有覆盖类User:

我的model.py:

class User(models.Model):
    username = models.CharField(max_length=30)
    password = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return self.username

我的view.py:

def post(self, request):
    form = self.form_class(request.POST)

    if form.is_valid():

        user = form.save(commit=False)
        print type(user)
        # Cleaning and normalizing data
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user.set_password(password)
        user.save()

        # returns User objects if the credential are correct
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('website:home')
    return render(request, self.template_name, {'form': form})

这是我的form.py:

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',
                                                             'type': 'password',
                                                             'placeholder': 'Enter your password'}))
    class Meta:
        model = models.User

我真的不知道是否应该覆盖User类。我应该在哪种情况下,在哪种情况下我不应该?

2 个答案:

答案 0 :(得分:3)

您需要继承AbstractUser才能访问set_password属性。而不是使用models.Model使用:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ...

您的User模型与django的User模型不同。

参考custom user model

答案 1 :(得分:0)

Django中的用户模型有.set_password,但是如果你自己创建了自己,你应该尝试OneToOneField(用户),你必须确保在视图中保存它们。

        user_form = UserForm(data=request.POST)
    if user_form.is_valid():
        user = user_form.save()
        user.set_password(user.password)
        profile = user.userprofile
        profile.bio = request.POST['bio']
        profile.save()