创建用户时列的数据太长

问题描述 投票:0回答:1

通过]

url(r'api/users/', views.MyUserCreate.as_view(), name='user-create'),

一个人可以看到DRF可浏览API

DRF Create Custom User Browsable API View

使用MyUserCreate(在views.py中)

class MyUserCreate(APIView):
    """ 
    Creates the user. 
    """

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            MyUser.objects.create_user(
                        serializer.username,
                        serializer.password
            )
            if user:
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

注意,它引用MyUserSerializer(在serializers.py中)

class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=MyUser.objects.all())],
            min_length=5,
            max_length=20
            ),
    password = make_password(serializers.CharField(
            write_only=True,
            required=True,
            max_length=256
            ))

    class Meta:
        model = MyUser
        fields = ('username', 'password')

    def create_user(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user

和MyUser(在models.py中)

class MyUserManager(BaseUserManager):
    def create_user(self, username, password):
        user = self.model(
            username=username
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    objects = MyUserManager()
    class Meta:
        # managed = False
        db_table = 'user_entity'

    user_id = models.AutoField(primary_key=True, db_column='userId')
    username = models.CharField(db_column='username', unique=True, max_length=20)
    password = models.CharField(db_column='userPassword', max_length=256)

    USERNAME_FIELD = 'username'

    def __str__(self):
        return str(self.user_id) + " (%s)" % str(self.username)

我发布以创建用户时

{
    "username": "tiagoperes",
    "password": "test"
}

我知道

django.db.utils.DataError:(1406,“数据对于列'username'而言过长在第1行“)

Django error Data too long for column 'username' at row 1

来自其他用户的信息,checked if the column is UTF8

UTF8 column

并且这里对于use TextField而不是CharField没有意义。

通过转到url(r'api / users /',views.MyUserCreate.as_view(),name ='user-create'),可以看到DRF可浏览API,该API使用MyUserCreate(在views.py中)类MyUserCreate( APIView):“”“ ...

python mysql django post django-rest-framework
1个回答
1
投票
  1. 您正在传递serializer.username
© www.soinside.com 2019 - 2024. All rights reserved.