Skip to content

Unable to make the ImageField as required in Swagger POST API #66

Closed

Description

@MounikaKommineni

My model:

class Image(models.Model):
      image=models.ImageField(upload_to='photos')
      name=models.CharField(max_length=40,unique=False)

My serializer:

class imagesSerializer(serializers.ModelSerializer):
      image = Base64ImageField(required=True)
      class Meta:
         model = Image
         fields = ('id','name','image')

My swagger view:
kfrof

How to make the imagefield as required in swagger post request ?

Activity

  1. johnthagen commented on Mar 4, 2019

    @johnthagen
    Contributor

    I noticed this too in generated Angular TypeScript. The image variables were always marked with ?, meaning they were optional.

  2. shafiyal commented on Mar 11, 2019

    @shafiyal

    I am also facing the same issue even though i specified required=True in serializer class

  3. baranugur commented on Mar 15, 2019

    @baranugur

    I'm using the same serializer setup and mine seems to be working fine. Maybe this is an issue of differences in versions. Here are the versions of Django, Django Extra Fields, Django REST Framework and Django REST Swagger that I have used, so you can compare: Django==2.1.7, django-extra-fields==1.0.0, djangorestframework==3.9.2, django-rest-swagger==2.2.0.

    swagger_correct

  4. johnthagen commented on Mar 15, 2019

    @johnthagen
    Contributor

    I wonder if it's because of the readOnly property? Would a readOnly property make it optional because it's not required when writing to the API? Is this because of how the file is normally returned as a URL rather than the data directly? (I'm just spit balling at this point).

  5. baranugur commented on Mar 15, 2019

    @baranugur

    ReadOnly fields cannot be required at the same time, therefore it's not possible to have a field where both required and read_only are set to True in the latest version of Django REST Framework.

  6. johnthagen commented on Mar 15, 2019

    @johnthagen
    Contributor

    What's weird is in my case, I never set read_only to True. The serializer is a WritableNestedSerializer, but I don't see how that would affect the field.

  7. baranugur commented on Mar 18, 2019

    @baranugur

    I've used the serializer below:

    class ImageSerializer(WritableNestedModelSerializer):
        image = Base64ImageField(required=True)
    
        class Meta:
            model = Image
            fields = ('id', 'name', 'image')
    

    It still seems to be working fine.

    swagger

  8. johnthagen commented on Mar 18, 2019

    @johnthagen
    Contributor

    @baranugur Could you also post your Image Model?

    I wonder why your image field doesn't say string($uri). That is how mine always is (and the OP's).

    Also, I'm using drf-yasg == 1.13.0 instead of django-rest-swagger due to django-rest-swagger having low maintenance as of late. Perhaps others in the thread could comment on which they are using.

  9. baranugur commented on Mar 19, 2019

    @baranugur

    The model that I've created is identical to OP's.

    I think drf-yasg==1.13.0 is causing the problem here. I've just tried it with Base64ImageField and then I've used the built-in serializers.ImageField; this is what I've gotten in both cases:

    yasg

  10. johnthagen commented on Mar 19, 2019

    @johnthagen
    Contributor

    Cross posted to axnsan12/drf-yasg#332

  11. johnthagen commented on Mar 19, 2019

    @johnthagen
    Contributor

    Confirmed this is drf-yasg specific (intended) behavior:

    axnsan12/drf-yasg#332 (comment)

    That is indeed the case. The field you linked breaks the contract of FileField by making it accept a string instead of an UploadedFile.

    You can work around this with a custom FieldInspector that returns an appropriate Schema object of type string, which should be placed before the FileFieldInspector.

  12. yigitguler commented on Apr 18, 2019

    @yigitguler
    Member

    Marking as completed.

  13. johnthagen commented on Apr 18, 2019

    @johnthagen
    Contributor

    @yigitguler There may be a way to work around this (at least in documentation): axnsan12/drf-yasg#332 (comment)

    I don't quite understand what needs to be done, but if this issue were left open it might be useful. We may be able to at least document how to make this work with drf-yasg, which I think would be valuable given it's the best maintained OpenAPI generator available for Django currently.

    Do you happen to understand the comment in the link above, and how we could fix it?

  14. 9 remaining items

  15. ilmesi commented on May 11, 2020

    @ilmesi

    @alicertel No problem! I got it from the code at FieldInspector.add_manual_fields from yasg. It seems to work pretty well and it's less work than creating a new FieldInspector..

  16. johnthagen commented on May 26, 2020

    @johnthagen
    Contributor

    I can confirm that @ilmesi's answer works. It seems like the most ideal work-around thus far.

    It would be good if this was documented somewhere officially.

  17. WasinTh commented on May 27, 2020

    @WasinTh
    Contributor

    @ilmesi Thank you for the suggestion. This seems pretty simple to me compered to creating a FieldInspector. What do you think @WasinTh ?

    Agreed. The solution to override Base64FileField is much more simple.

  18. alicertel commented on Aug 6, 2020

    @alicertel
    Contributor

    @WasinTh Would you like to update your PR #100 with the suggested solution #66 (comment) ?

  19. WasinTh commented on Aug 14, 2020

    @WasinTh
    Contributor

    @WasinTh Would you like to update your PR #100 with the suggested solution #66 (comment) ?

    @alicertel Sure. I've pushed the updated answer on those PRs.

  20. alicertel commented on Aug 14, 2020

    @alicertel
    Contributor

    Thanks @WasinTh

  21. Hassanzadeh-sd commented on Nov 25, 2020

    @Hassanzadeh-sd

    you should change your parser like this :

        from rest_framework import permissions, viewsets
        from rest_framework.mixins import (CreateModelMixin, DestroyModelMixin,
                                           ListModelMixin, RetrieveModelMixin)
        from rest_framework.parsers import FormParser, MultiPartParser
        from .models import Customer
        from .permissions import CustomerPermission
        from .serializer import CustomerSerializer
        
        
        class CustomerViewSet(CreateModelMixin, ListModelMixin, RetrieveModelMixin, 
                              DestroyModelMixin, viewsets.GenericViewSet):
            permission_classes = [CustomerPermission]
            queryset = Customer.objects.all()
            serializer_class = CustomerSerializer
            parser_classes = (FormParser, MultiPartParser)
    

    after that you can check your swagger :

    image

    I hope this can help you

  22. Krzyzaku21 commented on Jan 13, 2022

    @Krzyzaku21

    If you want create no class views but use drf:

    register_parameters = [openapi.Parameter(
        'date_of_birth', in_=openapi.IN_FORM, description='Add date like 2000-12-12', type=openapi.FORMAT_DATE,
        required=True)]
    
    
    @swagger_auto_schema(methods=['post'], request_body=RegisterSerializer, manual_parameters=register_parameters)
    @ api_view(['POST', ])
    @ parser_classes([parsers.MultiPartParser, parsers.FormParser])
    def user_register_serializer(request):
        if request.method == 'POST':
            new_data = {
                'response': f"Email send to {request.data['email']}",
            }
            serializer = RegisterSerializer(data=request.data)
            if serializer.is_valid():
                new_data.update(serializer.data)
                new_data.pop('password')
                serializer.save()
                user_email_send(request)
            else:
                new_data = serializer.errors
            return Response(new_data)
    

    using manual_parameters you can override form in swagger and add new functions like default etc to image.

  23. added a commit that references this issue on Oct 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions