I have this model containing an image field.
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=127)
logo = models.ImageField(upload_to='customer/logo', null=True, blank=True)
def __str__(self):
return self.name
In my view, I download the image from the specified url and store it in the image field. For testing, I use a test user as foreign key.
import json
import urllib.request
from django.core.files.base import ContentFile
from django.http import HttpResponse
from django.contrib.auth.models import User
from customer.models import Customer
def create(request):
values = json.loads(request.body.decode('utf-8'))
values['user'] = User.objects.get(id=1)
values['logo'] = ContentFile(urllib.request.urlopen(values['logo']).read(),
'test.png')
model = Customer.objects.create(**values)
return HttpResponse('Created customer with ' + str(values))
The image gets uploaded to customer/logo/test.png
as expected. Now, how can I display those images in the frontend? I could save them into the static files directory, but only the related user should be able to access it.
(By the way, Django admin interface shows that there is a file uploaded for the Customer
object. But it links to http://localhost:8000/admin/customer/customer/20/customer/logo/test.png
which is a wrong location and leads to a not found page.)
The files for
FileField
andImageField
are uploaded relative tosettings.MEDIA_ROOT
and should be accessible by the same relative filename appended tosettings.MEDIA_URL
. This is why your admin interface points to the wrong url. For security reasons these should be different thanSTATIC_ROOT
andSTATIC_URL
, otherwise Django will raise anImproperlyConfiguredError
.This will not prevent users from accessing files they shouldn't see, if they know or can guess the url. For this you will need to serve these private files through Django, instead of your web server of choice. Basically you need to specify a private directory under the web root level, and you need to load these files if the user has permission to see the file. E.g.:
In your view you will have to serve this file. One of the custom apps on my current project uses the following function to send static files:
And then use
send_file(customer.logo)
in your view.Django >= 1.5 should use the new
StreamingHttpResponse
instead ofHttpResponse
.