【发布时间】:2016-03-23 05:22:56
【问题描述】:
当我为我的应用注册新用户时,我正在尝试上传编码的 BASE64 图像,我在我的用户配置文件中使用了 ImageField 问题是 API 给了我以下错误。
{
"userprofile": {
"photo": [
"The submitted data was not a file. Check the encoding type on the form."
]
}
}
这是我在请求中的信息,我使用带有标头 Content-Type: application/json 的 POST 请求我使用来自 google 的 POSTMAN
{
"username": "is690002",
"password": "is690002",
"first_name": "andres ",
"last_name": "Barragan",
"email": "zaturoz.marco@gmail.com",
"userprofile": {
"gender": "F",
"phone_number": "3315854644",
"photo": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYAB......."
}
}
这是我的model.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',message="Phone must be entered in the format: '+999999999'. Up 15 digits allowed.")
#The Field on DataBase after check if it's a valid Phone Number.
# validators should be a list
phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True)
photo = models.ImageField(upload_to = 'C:\ProjectsDJ\carpoolapp\photos', null = True)
我的序列化器
class UserProfileSerializer(serializers.ModelSerializer):
photo = serializers.ImageField(max_length=None, use_url=False)
class Meta:
model = UserProfile
fields = (
'gender',
'phone_number',
'photo'
)
class UserRegistrationSerializer(serializers.HyperlinkedModelSerializer):
userprofile = UserProfileSerializer()
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password',
'userprofile'
)
extra_kwargs = {'password': {'write_only': True}}
#@Override create for create a user and profile from HTTP Request
def create(self, validated_data): #
userprofile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data) # Create the user object instance before store in the DB
user.set_password(validated_data['password']) #Hash to the Password of the user instance
user.save() #Save the Hashed Password
UserProfile.objects.create(user=user, **userprofile_data)
return user #Return user object
还有我的 View.py
class UserRegister(APIView):
permission_classes = ()
def post(self, request):
serializer = UserRegistrationSerializer(data = request.data) #, files = request.FILES)
serializer.is_valid(raise_exception=True) # If the JSON Is
serializer.save() #Save user in DB
return Response(status=status.HTTP_201_CREATED)
注意:如果我不使用 imageField 我可以创建我的用户等,一切都很好,我也在 StackOverflow 中尝试了两个教程
【问题讨论】:
-
检查 github 中的 DRF 测试。这可能会对您有所帮助。 github.com/tomchristie/django-rest-framework/blob/…
标签: python json django django-rest-framework