Upload multiple images in Django Admin

2019-06-11 23:17发布

models.py

class Video(models.Model):
    title = models.CharField(max_length=100, blank=True, default='')
    details = models.TextField()

class VideoDetails(models.Model):
    video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='videos')
    images = models.ImageField(upload_to='images/video/%Y/%m/%d')

serializers.py

class VideoDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = VideoDetails
        fields = '__all__'

class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Video
        fields = '__all__'

admin.py

class VideoDetailsInline(admin.TabularInline):
    model = VideoDetails

class VideoAdmin(admin.ModelAdmin):
    inlines = [VideoDetailsInline]

admin.site.register(Video, VideoAdmin)

enter image description here enter image description here

As shown above, I uploaded 3 images for video 2. However, in my VideoList view, I didn't get the urls of those images.

views.py

class VideoList(viewsets.ModelViewSet):
    serializer_class = VideoSerializer
    queryset = Video.objects.all()

How can I attach those image url in VideoDetail to the queryset of Video? Need your help...

1条回答
老娘就宠你
2楼-- · 2019-06-12 00:03

Change your files according to that and don't forget configure a MEDIA_URL

models.py

import os
from django.conf import settings

class VideoDetails(models.Model):
    video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='videos')
    images = models.ImageField(upload_to='images/video/%Y/%m/%d')

    def get_absolute_image_url(self):
        return os.path.join(settings.MEDIA_URL, self.images.url)

serializers.py

class VideoDetailsSerializer(serializers.ModelSerializer):

    image_url = serializers.URLField(source='get_absolute_image_url', read_only=True)

    class Meta:
        model = VideoDetails
        fields = ('video', 'image_url')


class VideoSerializer(serializers.ModelSerializer):

    video_details = VideoDetailsSerializer(many=True, read_only=True)

    class Meta:
        model = Video
        fields = ('title', 'details', 'video_details')
查看更多
登录 后发表回答