3

Currently I am trying to use an imageField to pass images from my model to an endpoint, but I don't know how to go about it.

Here is my model:

class searchResultsItem(models.Model):
    """
    Model to store search results item for a tableView cell
    """
    title = models.CharField(max_length = 100)
    price = models.CharField(max_length = 4)
    pop = models.IntegerField(default = 0)
    distance = models.CharField(max_length = 10)
    image = models.ImageField(upload_to="/media",default="/media")

Here is my view:

class searchResultsItemViewSet(viewsets.ModelViewSet):
    """
    API or Endpoint that can be viewed or edited
    """
    queryset = searchResultsItem.objects.all()
    serializer_class = searchResultsItemsSerializer

Here is my serializer:

class searchResultsItemsSerializer(serializers.ModelSerializer):
    """
    Serializer to parse searchResultsCell data
    """
    image = serializers.ImageField(
            max_length = None, use_url=True
        )

    class Meta:
        model = searchResultsItem
        fields = ('title','price','pop','distance','image')

Here is my urls:

from panView.searchTableData import views

router = routers.DefaultRouter()
router.register(r'searchResultsItem',views.searchResultsItemViewSet)

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

However, when I look at my endpoint I get a 404 error for the url of the image. The images are located in a media directory above my app folder and in my project folder. The text objects work just not the images.

If anyone knows how to pass images from the Django rest framework to an endpoint using imageField I'd like guidance for that.

1 Answers1

1

serializer.ImageField

This returns absolute url of the image, what we need is the relative url. You can do following for that-

class searchResultsItemsSerializer(serializers.ModelSerializer):
    """
    Serializer to parse searchResultsCell data
    """
    image = serializers.SerializerMethodField()

    def get_image(self, instance):
        # returning image url if there is an image else blank string
        return instance.image.url if instance.image else ''

    class Meta:
        model = searchResultsItem
        fields = ('title','price','pop','distance','image')

Docs for SerializerMethodField

Hope this helps.

Saurabh Goyal
  • 605
  • 4
  • 21
  • Thanks! That does give me a relative url, but still not the right url. I'm relatively new to django. I feel as if my directory structure isn't setup properly – Sasikanth Kavuri Aug 26 '15 at 19:19