使用django rest_framework时基于自定义用户的令牌认证

时间:2017-02-07 14:47:35

标签: python django

我有注册页面,用户注册他们的数据。我需要在注册时向注册用户提供令牌,为此我有用户模型,我在已安装的应用中添加了rest_framework.authtoken和{ {1}},DEFAULT_PERMSSION中的AUTH_USER_MODEL,我在User类中拥有所有者字段,当我尝试注册时收到此错误settings.pyIntegrityError

views.py

(1048, "Column 'owner_id' cannot be null")

models.py

def transregister(request):
    if request.POST:
        args = {}
        args.update(csrf(request))
        # try:

        if request.method == 'POST':

            user = UserForm(request.POST)
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password']
            confirm_pwd = request.POST['confirm_pwd']
            company_name = request.POST['company']

            profile_type = request.POST['trainer-company']

            trainerprofile = TrainerForm(request.POST)

            corporate_profile = CorporateProfileForm(request.POST)
            print username


            if user.is_valid():
                userModel = user.save(commit=False)
                userModel.is_user = True
                userModel.is_active=True
                userModel.save()

serializers.py

class User(models.Model):
    username = models.CharField(max_length=150)
    #username = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.CharField(max_length=250,unique=True)
    company = models.CharField(max_length=250)
    password = models.CharField(max_length=150)
    confirm_pwd = models.CharField(max_length=150)
    is_admin = models.BooleanField(default=False)
    is_user = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    device_id = models.CharField(max_length=1000, blank=True, null=True)

  #  User = get_user_model()
    user = settings.AUTH_USER_MODEL
    owner = models.ForeignKey('user', related_name='User', on_delete=models.CASCADE)
    highlighted = models.TextField(default = '')

    objects = UserManager()

    #class Meta:
    #    db_table = u'index_user'


    REQUIRED_FIELDS= ('username',)
    USERNAME_FIELD = ('email')

    def __str__(self):
        return self.username

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

1 个答案:

答案 0 :(得分:1)

在settings.py中,您需要配置身份验证类以包含TokenAuthentication。

要在settings.py中设置它,您应该使用:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

既然您还要创建自己的用户模型,则需要为引用自定义模型的AUTH_USER_MODEL设置提供一个值:

AUTH_USER_MODEL = 'myapp.MyUser'