1

I'm new with Django and I have a problem I hope you can help me to solve.

First of all, I'm working with Django 1.8.3 and Python 2.7.6 on a Virtual Env using Apache and Postgres as my DBMS.

I have the following model on my models.py file:

class Hotel(models.Model):
    # ...
    name = models.TextField(blank=True, null=True)
    img = models.ImageField(upload_to='images/',blank=True, null=True)
    stars = models.IntegerField(blank=True, null=True)
    # ...

class Meta:
    managed = False
    db_table = 'hotel'

My views.py file looks like this

from django.http import HttpResponse, Http404
from webServices.models import Hotels
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
import json
# ...
def all_hotels(request):
    hotels = Hotel.objects.values('name', 'img', 'stars')
    data = json.dumps(list(hotels), indent = 4)

    return HttpResponse(data, content_type='application/json')

And my MEDIA_URL and MEDIA_ROOT variables on settings.py file are defined as follows:

MEDIA_URL = '/media/'

MEDIA_ROOT = '/path_to_my_projects_directory/media/'

As you can see, I'm working on a server that returns a json with the data for every hotel in the DB. It certainly works fine.

Json's img field has been 'null' until now that I need to associate every image stored locally to its hotel and return its URL in it.

The problem is I don't know how.

It's good to know as well that the DB is updated via python script since the data reside in a Google SpreadSheet (I'll show you if asked).

I've been searching all day long and I've found this post how to manually assign imagefield in Django and this article http://www.revsys.com/blog/2014/dec/03/loading-django-files-from-code/, but I need them to be a little bit more specific.

Community
  • 1
  • 1

1 Answers1

0

Hi try this one in your views.py

from django.conf import settings

url = request.scheme
url += "://"
url += request.META['HTTP_HOST']
url += settings.MEDIA_URL
_len = len(hotels)
_range = range(0, _len)
hotels = Hotel.objects.values('name', 'img', 'stars')
for x in _range:
    hotels[x]['img'] = "%s%s" % (url, hotels[x]['img'])

data = json.dumps(list(hotels), indent = 4)
return HttpResponse(data, content_type='application/json')
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116