python - 想要显示图像

标签 python mysql sql database django

我有一个小问题。我想要一个可以上传和显示图像的 django 应用程序。目前,它可以上传图片,但我无法显示该图片。

例如,{{comment.photo}} 将打印出路径 C:/Users/AQUIL/Desktop/myproject/images/P1000992.JPG。但我想在屏幕上看到那个图像。不是路径。如何将图像打印到屏幕上?

以下是一些可能有帮助的信息。

模型.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 %}

最佳答案

{% if comment.photo %} <img src="{{ comment.photo.url }}" alt="Photo" /> {% endif %}

有关如何正确上传图片的信息,请参阅 Geoffrey 的评论。

关于python - 想要显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6777732/

相关文章:

python - Python中List的组合项

mysql - ActiveRecord 为与 MySQL 的 has_and_belongs_to_many 关系生成昂贵的 DESCRIBE 查询

mysql - 从 3 个表中选择

MySql 全文搜索对于短单词不正确

php - 如何获取一张表中的选定元素?

php - 这两个查询哪一个更快?

python - 在python中按顺序重命名文件

python - 我如何阅读 numpy 源代码?

python - 从维基百科转储中提取平行文本

javascript - 将 node.js 变量导入数据库