[英]Django serving images from database
I am adding trying to get an app to serve image fields in my database to display in my template. 我正在添加尝试获取应用程序以在我的数据库中提供图像字段以显示在我的模板中。 I was wondering if there was a way to bypass having to use a global media dir/url setting, for the sake of organization.
为了组织起见,我想知道是否有办法绕过必须使用全局媒体目录/网址设置。 In my modal i have set and upload to option.
在我的模态中,我已设置并上传到选项。 Id like to use a url mapping for the app with regex named groups to tell my view what the path and the image name is.
我喜欢使用带有正则表达式命名组的应用程序的URL映射来告诉我的视图路径和图像名称是什么。 concatenate that into a string and serve back the file.
将其连接成一个字符串并回送该文件。 If this is a terrible idea, or is just grossly inefficient, I'll just do something else.
如果这是一个可怕的想法,或者只是非常低效,我会做其他事情。 Any help is greatly appreciated.
任何帮助是极大的赞赏。 Here is what I have so far.
这是我到目前为止所拥有的。
Template:` 模板:`
{% for category in items %}
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="{{ category.picture }}" />
<div class="caption">
<h4 class="pull-right">${{ category.price }}</h4>
<h4><a href="#">{{ category.itemName }}</a>
</h4>
</div>
</div>
</div>
{% endfor %}
Models.py: Models.py:
from django.db import models
class StoreCategory(models.Model):
categoryName = models.CharField(max_length=128)
def __unicode__(self):
return self.categoryName
class StoreItem(models.Model):
category = models.ForeignKey(StoreCategory)
itemName = models.CharField(max_length=128)
description = models.CharField(max_length=1024)
price = models.DecimalField(max_digits=16,decimal_places=2)
quantity = models.IntegerField(default=0)
picture = models.ImageField(upload_to='store_images', blank=False)
def __unicode__(self):
return self.itemName
Urls.py: Urls.py:
urlpatterns = patterns('',
url(r'^$', views.webstore, name='webstore'),
url(r'^FiberArts/$', views.FiberArts, name='FiberArts'),
url(r'^FiberArts/(?P<directory>[\w]+)/(?P<image_name>[\w]+)$',views.getImage)
)
View: ( currently this is never called, problem with regex?) 查看:(目前这个从未被调用,正则表达式的问题?)
def getImage(request, directory, image_name):
imagelocation = directory + '/' + image_name
print imagelocation
image_data = open(imagelocation, "rb").read()
return HttpResponse(image_data, mimetype="image/png")
Edit: Here is the error I'm getting: 编辑:这是我得到的错误:
[06/Apr/2014 15:48:35] "GET /webstore/FiberArts/store_images/product_150_1.jpg HTTP/1.1" 404 3743
Change that url regex to this (?P<directory>[\\w]+)/(?P<image_name>[\\w]+\\.[\\w]+)$'
and fix your view to accept the right number of arguments. 将该url正则表达式更改为此
(?P<directory>[\\w]+)/(?P<image_name>[\\w]+\\.[\\w]+)$'
并修复您的视图以接受正确的数字参数。 You should now receive the right image_name
inside your view. 您现在应该在视图中收到正确的
image_name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.