我正在使用Django 1.8.4和Django rest framework 3.2.3。因为我想覆盖"用户名"我必须使用" AbstractBaseUser" 使用的模型是:
class Users(AbstractBaseUser):
username = models.EmailField(max_length=75, null=False, blank=False, unique=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=70, null=True, blank=True)
tel_number = models.IntegerField(null=True, blank=True)
address = models.CharField(max_length=250, null=True, blank=True)
user_image = models.ImageField(upload_to='user_avatar', blank=True, null=True)
date_time = models.DateTimeField(auto_now=True, null=True, blank=True)
activated = models.BooleanField(default=False)
def __unicode__(self):
return self.username
class Meta:
ordering = ['-id']
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['tel_number']
现在我想用新令牌创建新用户:
if request.method == 'POST':
serializer = UserSerializer(data=request.data)
data = {}
if serializer.is_valid():
user = serializer.save()
token, created = Token.objects.get_or_create(user=user)
data['token'] = token
data = serializer.data
return Response(data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我的序列化器是:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ('id', 'username', 'password', 'first_name', 'last_name', 'tel_number', 'address', 'user_image')
但我在"创建令牌行":
时收到此错误Cannot query "a@gmail.com": Must be "User" instance.
答案 0 :(得分:1)
您没有将用户实例传递给Token。 你能试试这个:
在routers.py
中from rest_framework import routers
from .viewsets import UserSeralizerViewSets
router = routers.DefaultRouter()
router.register(r'users', UserSeralizerViewSets)
在urls.py
from .routers import router
urlpatterns = [
url(r'^', include(router.urls)),
]
在viewsets.py
中class UserSeralizerViewSets(viewsets.ModelViewSet):
serializer_class = UserSeralizer
queryset = Users.objects.all()
def create(self, request, *args, **kwargs):
data = {}
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
token, created = Token.objects.get_or_create(user=user)
data['token'] = token.key
return Response(data, status=status.HTTP_201_CREATED)
答案 1 :(得分:0)
seeu s 的答案很好,但我在settings.py中使用这一行并且有效。
AUTH_USER_MODEL = 'users.Users'
Users.Users是(myappname.mymodelname)
我在Django doc上找到了这个。