【发布时间】:2018-12-15 19:12:27
【问题描述】:
我正在学习 Django,目前正在尝试制作一个简单的网站,用户可以在其中发布主题和内容。我想要的只是打开主题时显示的属于某个主题的上传图片。但是我现在非常坚持,我无法在页面上显示任何图像。我尝试了很多不同的东西,但到目前为止都没有奏效。我无法理解模板应该是什么样子以及如何将其链接到主题页面......我的观点可能与正确的观点相去甚远,但我已经尝试了很多事情并且它都有一个有点乱......几乎已经有 2 天的麻烦了,我将不胜感激任何指示 提前谢谢你
这就是我所拥有的:
models.py
class Image(models.Model):
"""images representation"""
image=models.ForeignKey(Topic, on_delete=models.CASCADE)
image=models.ImageField(upload_to= 'media/')
caption=models.CharField(max_length= 100)
uploaded_at=models.DateTimeField(auto_now_add=True)
views.py
def upload_image(request, topic_id):
"""Upload images"""
topic=Topic.objects.get(id=topic_id)
if request.method != 'POST':
# No data submitted; creaete a blank form
form=ImageForm()
else:
# Data submitted; Process data
form=ImageForm(request.POST, request.FILES)
if form.is_valid():
instance=form.save(commit=FALSE)
instance.topic=topic
instance.save()
return HttpResponseRedirect(reverse('the_horror:topic',
args=[topic_id]))
images=Image.objects.all()
context={'form':form, 'topic':topic, 'images':images}
return render(request, 'the_horror/topic.html', context)
上传图片.html
{% extends 'the_horror/base.html' %}
{% block content %}
{% if images %}
<ul>
{% for image in images %}
<li>
<a href="{{image.image.url}}">
<img source="{{image.image.url}}" alt="sth"></a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<form action="{% url 'upload_image' %}" method= "post" enctype= "multipart/form-data">
{% csrf_token %}
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
<button type="submit">name="upload photo"</button>
</form>
正如我所说,我不确定如何将图像传递给主题模板
topic.html
{% extends 'the_horror/base.html' %}
{% block content %}
<p>Topic:{{topic}}</p>
<p>
<a href="{% url 'the_horror:edit_topic' topic.id %)">edit topic</a>
</p>
<p>Entries</p>
<p>
<a href="{% url 'the_horror:new_entry' topic.id %}">Add a new entry</a>
</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{entry.text|linebreaks}}</p>
<p>
<image class= "Image" source={{>
</p>
<p>
<a href="{% url 'the_horror:edit_entry' entry.id %}">edit entry</a>
</p>
</li>
{% empty %}
<li>
There are no entries for this topic yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
urls.py
path('upload_image/<topic_id>', views.upload_image, name= 'upload_image'),
# Single topic page
【问题讨论】:
标签: django image file-upload