在Django中显示用户的图像

时间:2018-07-07 11:45:53

标签: django image file-upload

我正在学习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)

upload_image.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

1 个答案:

答案 0 :(得分:0)

在您的models.py上,您无需在upload_to选项上写入媒体,您要做的就是在此处添加到urls.py static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urls.py

urlpatterns = [
  ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

为什么在您的upload_image.html上创建2个输入。我个人使用输入来获取图像文件

upload_image.html

...
<input name="image" type="file">
...

然后在视图中启动得很好,但我将按照以下步骤存储图像

views.py

def upload_image(request, topic_id):
    ...
    imageObject = Image.objects.create()
    image = request.FILES['image']
    imageObject.image = image
    ...

最后,您将以这种方式获取图片

topic.html

<img src="{{MEDIA_URL}}{{imageObject.image}}" alt="image">

通常可以,如果您仍然有错误或问题让我知道,我使用这种方法或类似方法制作了多个项目