I am now getting the file from my front-end and I set my model like this.
model.py
class User(models.Model):
name = models.CharField(max_length=50)
image= models.FileField(upload_to='image/', default=None)
intro= models.FileField(upload_to='info/', default=None)
view.py
class UserViewSet(viewsets.ModelViewSet):
serializer_class = LsRequestSerializer
queryset = User.objects.all()
http_method_names = ['post']
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
field = '__all__'
def create(self, validated_data):
newUser = User.objects.create(
name = validated_data['name']
image = validated_date['image']
intro = validated_date['intro']
)
return newUser
However, when I did the HTTP.POST in Postman, it gave the wrong path to save the image.
"http://localhost:8000/media/Koala.jpg"
But based on my design in the model with path_to, it should give:
"http://localhost:8000/media/image/Koala.jpg"
Update: The strange thing is that when I tried to update a user by giving a new image using HTTP.Patch method, it then has the right path.
Update: It turns out to be the problem that I cannot have multiple input filefield and upload_to different subfolders. How to solve this problem? If I put the serializer as above, it can find the right path but it also means that these two fields are required. But in fact, these two fields are optional. But if I put the if statement outside the create function, it cannot detect the correct path. class UserSerializer(serializers.ModelSerializer): class Meta: model = User field = 'all'
def create(self, validated_data):
newUser = User.objects.create(
name = validated_data['name']
image = None
intro = None
)
if validate_data['image']:
newUser.image = validate_data['image']
if validate_data['intro']:
newUser.image = validate_data['intro']
return newUser
What's wrong with my code?