Django休息框架自定义用户模型,带有令牌错误

时间:2018-03-11 15:16:49

标签: django django-models

我尝试使用自定义用户模型而不是默认用户。

我的Django项目结构如下。

  • 项目名称:project_rest
  • 应用程序名称:app_rest

要实现这一目标,请参考https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model

[settings.py]

AUTH_USER_MODEL = 'app_rest.User'

[models.py]

from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from django.contrib.auth.models import AbstractUser

@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)

class User(AbstractUser):
    username = models.CharField(unique=True, null=False, max_length=254)
    password = models.CharField(max_length=200)

[serializers.py]

from app_rest.models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password')

[views.py]

from django.shortcuts import render
from app_rest.serializers import UserSerializer
from app_rest.models import User
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

[urls.py]

from django.conf.urls import url, include
from app_rest import views
from rest_framework import routers
from django.contrib import admin
from rest_framework.authtoken import views as rest_views

router = routers.DefaultRouter()
router.register(r'user', views.UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^token-auth/', rest_views.obtain_auth_token),
    url(r'^admin/', admin.site.urls),
]

我似乎工作正常,但是当我删除用户时,它会抛出错误。

  

IntegrityError at / admin / app_rest / user / 1 / delete /(1452,'无法添加或   更新子行:外键约束失败   ('休息'。'django_admin_log',CONSTRAINT   'django_admin_log_user_id_c564eba6_fk_auth_user_id'外键   ('user_id')REFERENCES'auth_user'('id'))')

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

错误非常自我解释。您尝试删除的记录与外键相关,并且无法删除,因为它会破坏参照完整性。

您需要使用ON DELETE CASCADE或其等价物来更改该ID,或者允许用户在相关表格上为空(如果可能的话)。