【发布时间】:2014-06-20 21:17:35
【问题描述】:
我有一个包含图像字段的模型。
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
在我看来,我从指定的 url 下载图像并将其存储在图像字段中。对于测试,我使用测试用户作为外键。
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))
图片按预期上传到customer/logo/test.png。现在,如何在前端显示这些图像?我可以将它们保存到静态文件目录中,但只有相关用户才能访问它。
(顺便说一下,Django 管理界面显示有一个为Customer 对象上传的文件。但它链接到http://localhost:8000/admin/customer/customer/20/customer/logo/test.png,这是一个错误的位置并导致一个未找到的页面。)
【问题讨论】:
标签: python django file-upload permissions static-files