如何在自定义非管理模型中使用“set_password”?

时间:2018-03-22 14:42:45

标签: python django django-models string-hashing

我想在django.contrib.auth.models中使用来自用户模型的哈希字段set_password,而我目前正在使用自定义用户模型。

我收到以下错误:Attribute error: 'User' object has no attribute 'set_password'

models.py

from django.db import models


class User(models.Model):
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    profile_picture = 
     models.ImageField(upload_to="user_data/profile_picture", blank=True)
    username = models.CharField(max_length=100)
    birth_date = models.DateField(blank=True)
    gender = models.CharField(max_length=10, blank=True)
    password = models.CharField(max_length=1000)
    contact = models.CharField(max_length=10, blank=True)
    email = models.CharField(max_length=100)
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.username

views.py

...
from .models import User

...
    def post(self, request):
        # Data is here
        form = self.form_class(request.POST)
        if form.is_valid():
            # create object of form
            user = form.save(commit=False)

            # cleaned/normalised data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # convert plain password into hashed
            user.set_password(user.password)
            user.save()

            return HttpResponse('Done here.')
            ...

forms.py (仅在forms.py中使用了一个小部件)

from .models import User
from django import forms


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

    class Meta:
        model = User
        fields = ['username', 'password']

1 个答案:

答案 0 :(得分:2)

这是一个非常简单的修复方法。只需更改您的models.py文件:

from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True)
    username = models.CharField(max_length=100)
    birth_date = models.DateField(blank=True)
    gender = models.CharField(max_length=10, blank=True)
    password = models.CharField(max_length=1000)
    contact = models.CharField(max_length=10, blank=True)
    email = models.CharField(max_length=100)
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.username

这样,您的用户模型将继承所有AbstractBaseUser方法,包括set_password

从文档中查看此full example以获取更多信息。