Reputation: 1607
I am having a slight problem. I want a django app that can upload and display an image. Currently, it can upload the image but I cannnot display that image.
So for example, {{comment.photo}} will print out the path C:/Users/AQUIL/Desktop/myproject/images/P1000992.JPG
. But I want to see that image on the screen. Not the path. How do I print out the image to the screen?
Here is some information that may help.
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 %}
Upvotes: 1
Views: 856
Reputation: 951
The upload parameter of ImageField must be a local path, so replace:
photo = models.ImageField(upload_to='C:/Users/AQUIL/Desktop/myproject/media/images', blank=True, null=True)
by:
photo = models.ImageField(upload_to='images', blank=True, null=True)
Then set the MEDIA_ROOT in settings.py as:
MEDIA_ROOT = 'C:/Users/AQUIL/Desktop/myproject/media/'
Finally your image 'myImage.png' will be accessible at:
C:/Users/AQUIL/Desktop/myproject/media/images/myImage.png
And this tag should load the image:
<img src="/media/images/myImage.png" alt=""/>
depends of your MEDIA_URL in settings.py which should be:
MEDIA_URL = '/media/'
Upvotes: 4
Reputation: 176780
{% if comment.photo %} <img src="{{ comment.photo.url }}" alt="Photo" /> {% endif %}
See Geoffrey's comment for how to upload the image correctly.
Upvotes: 4