Reputation: 139
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?
Upvotes: 0
Views: 1374
Reputation: 56
Well you should first check that if you specified the right path for media in your setting.py
it should be something like this:
The place that you want to store those pictures:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
And as you want to see them like "http://localhost:8000/media/whatever/whatever.jpg"
you should specified the MEDIA_URL
like this:
MEDIA_URL = '/media/'
And then as you did it in your models the argument will be like:
upload_to='image/'
You can also read more about it here!
And as a side note if you want to deal with pictures then you can use ImageField
rather than FileField
.
Upvotes: 1