我有一个小问题。我想要一个可以上传和显示图像的django应用程序。目前,它可以上传图像,但我无法显示该图像。
例如,{{comment.photo}}将打印出路径C:/Users/AQUIL/Desktop/myproject/images/P1000992.JPG
。但我想在屏幕上看到那个图像。不是路径。如何将图像打印到屏幕上?
以下是一些可能有用的信息。
models.py
class Comment(models.Model):
name = models.CharField(max_length = 40)
datetime = models.DateTimeField(default=datetime.now)
photo = models.ImageField(upload_to='C:/Users/AQUIL/Desktop/myproject/media/images', blank=True, null=True)
note = models.TextField()
def __unicode__(self):
return unicode(self.name)
views.py
def home(request):
comments = None
try:
comments = Comment.objects.order_by('-datetime')
except:
return HttpResponseNotFound()
return render_to_response('home.html', {'comments':comments}, context_instance=RequestContext(request))
def add_notes(request):
comments = Comment.objects.all()
if request.method == 'POST':
form = CommentForm(request.POST or None, request.FILES)
if form.is_valid():
comments.datetime = datetime.now()
form.save(True)
return HttpResponseRedirect(reverse(home))
else:
form = CommentForm()
return render_to_response('form.html', {'form':form,'comments':comments}, context_instance = RequestContext(request))
home.html的
{% extends "base.html" %}
{% block content %}
<H2>List of Comments</H2>
<div style="overflow:auto;padding: 10px; border:1px solid black; height:150px; width:700px;">
{% for comment in comments %}
{{comment.photo}} <br/>
<b>Posted by: {{ comment.name }} Date: {{ comment.datetime.date }} Time: {{comment.datetime.time}}</b><br/>
<div style="font-size:125%">{{ comment.note }}</div><br/>
{% endfor %}
</div>
{% endblock %}
form.html
{% extends "base.html" %}
{% block content %}
<h3>Add Notes</h3>
<form enctype="multipart/form-data" action="" method="POST">
{% csrf_token %}
<table>
{{form.as_table}}
<br/>
</table>
<input type="submit" value="Save" STYLE="background-color:#E8E8E8; color:#181818 "/>
</form>
{% endblock %}
答案 0 :(得分:4)
{% if comment.photo %} <img src="{{ comment.photo.url }}" alt="Photo" /> {% endif %}
请参阅Geoffrey关于如何正确上传图片的评论。
答案 1 :(得分:4)
ImageField的upload参数必须是本地路径,因此请替换:
photo = models.ImageField(upload_to='C:/Users/AQUIL/Desktop/myproject/media/images', blank=True, null=True)
由:
photo = models.ImageField(upload_to='images', blank=True, null=True)
然后将settings.py中的MEDIA_ROOT设置为:
MEDIA_ROOT = 'C:/Users/AQUIL/Desktop/myproject/media/'
最后,您的图片'myImage.png'将在以下位置访问:
C:/Users/AQUIL/Desktop/myproject/media/images/myImage.png
此标记应加载图片:
<img src="/media/images/myImage.png" alt=""/>
取决于您的MEDIA_URL在settings.py中应该是:
MEDIA_URL = '/media/'
答案 2 :(得分:0)