django rest的可浏览api中未显示上传的图片网址

时间:2018-10-07 08:51:40

标签: python django django-rest-framework

以下是我的Django rest API的不同部分

项目结构

project structure

settings.py

...

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

...

accounts / models.py / Profile

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField(upload_to="images/", null=True, blank=True)
    contact_number = models.CharField(validators=[contact_number_validator], max_length=16, blank=True, null=True)
    address = models.CharField(max_length=30, blank=True, null=True)
    birth_date = models.DateField(null=True, blank=True)
    USER_TYPES = (
        ('o', 'Owner'),
        ('c', 'Customer'),
        ('e', 'Employee'),
    )
    user_type = models.CharField(
        max_length=1,
        choices=USER_TYPES,
        blank=True,
        default='c',
        help_text='User Role',
    )

    saloon = models.ForeignKey(Saloon, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return '{}\'s profile'.format(self.user.username)

api / views.py / UpdateUserProfileView

class UpdateUserProfileView(generics.RetrieveUpdateAPIView):
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticated, CanUpdateUserProfile)

    def get_queryset(self):
        return Profile.objects.filter(user=self.request.user).values(
            'user__username',
            'user__email',
            'user__first_name',
            'user__last_name',
            'user_type',
            'birth_date',
            'contact_number',
            'address',
            'profile_picture',
        )

    def perform_update(self, serializer):
        profile = get_object_or_404(Profile, user=self.request.user)
        user = get_object_or_404(User, id=profile.user.id)

        user.username = serializer.validated_data['user__username']
        user.first_name = serializer.validated_data['user__first_name']
        user.last_name = serializer.validated_data['user__last_name']
        user.email = serializer.validated_data['user__email']
        user.save()

        profile.contact_number = serializer.validated_data['contact_number']
        profile.birth_date = serializer.validated_data['birth_date']
        profile.address = serializer.validated_data['address']
        profile.profile_picture = serializer.validated_data['profile_picture']
        profile.save()

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    profile_picture = serializers.ImageField(max_length=None, use_url=True)
    username = serializers.CharField(source='user__username')
    first_name = serializers.CharField(source='user__first_name')
    last_name = serializers.CharField(source='user__last_name')
    email = serializers.EmailField(source='user__email')

    class Meta:
        model = Profile
        depth = 1
        fields = (
            'username', 'first_name', 'last_name', 'email', 'contact_number', 'birth_date', 'user_type',
            'address', 'profile_picture',
        )
        #fields = '__all__'
        read_only_fields = ('user_type',)

项目级网址

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^', include('api.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

输出

api output

问题

图像URL未在输出中显示 图像已成功上传到所需的文件夹中 并且数据库已成功更新。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,因为如下所示,我在序列化程序中更改了 profile_picture 字段,并为URL添加了一个额外的字段,并在单独的字段中为其分配了值。 就我在google上搜索而言,我发现该URL应该自动生成,但就我而言,我必须手动构建它。 如果有人知道另一种方式,请告诉我。

class UserProfileSerializer(serializers.ModelSerializer):
    profile_picture = serializers.ImageField(max_length=None, use_url=True, write_only=True)
    username = serializers.CharField(source='user__username')
    first_name = serializers.CharField(source='user__first_name')
    last_name = serializers.CharField(source='user__last_name')
    email = serializers.EmailField(source='user__email')

    profile_picture_url = serializers.SerializerMethodField()

    def get_profile_picture_url(self, obj):
        request = self.context['request']
        return request.build_absolute_uri(MEDIA_URL + obj['profile_picture'])

    class Meta:
        model = Profile
        depth = 1
        fields = (
            'username', 'first_name', 'last_name', 'email', 'contact_number', 'birth_date', 'user_type',
            'address', 'profile_picture', 'profile_picture_url',
        )
        # fields = '__all__'
        read_only_fields = ('user_type',)