我有一个可以使用的注册API,但是我希望能够在注册用户时上传可选图像。当前,我收到一个错误:“ TypeError:'photo'是此函数的无效关键字参数”。这是我的代码:
# serializers.py
class RegisterSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
email = serializers.EmailField(required=True)
photo = serializers.ImageField() # doesn't work currently
class Meta:
model = User
fields = ('id', 'username', 'first_name',
'last_name', 'email', 'photo', 'password')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
user = super(RegisterSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
# api.py
class RegisterAPIView(CreateAPIView):
serializer_class = RegisterSerializer
permission_classes = [AllowAny]
parser_class = (FileUploadParser,) # not sure if this is needed
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
token = Token.objects.create(user=serializer.instance)
token_data = {"token": token.key}
return Response({**serializer.data, **token_data})
# urls.py
urlpatterns = [
path('api/auth/register', RegisterAPIView.as_view()),
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")