[英]how can I add Image to my django database and display it in frontend
I am making a blogging website in Django.我正在 Django 中创建一个博客网站。 I want to add a functionality with which the user can upload an image in the form, which will be used as a thumbnail for that blog.
我想添加一个功能,用户可以使用该功能上传表单中的图像,该图像将用作该博客的缩略图。 I have added
imageField
in models.py file, now I am not getting how shall I take the image input from the user in the form section?我在models.py文件中添加了
imageField
,现在我不知道如何在表单部分从用户那里获取图像输入?
post models.py:发布models.py:
class Post(models.Model):
sno = models.AutoField(primary_key=True)
thumbnail = models.ImageField(null=True, blank=True, upload_to="images/")
title = models.CharField(max_length=50)
content = RichTextField(blank=True, null=True)
author = models.CharField(max_length=50)
slug = models.CharField(max_length=200)
timeStamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timeStamp']
def __str__(self):
return self.title + " by " + self.author
html forms: html表格:
<form action = "{% url 'addblog' %}" method="post">
<div class="form-group">
<label for="title" id="Title">Title</label>
<input type="text" class="form-control" id="title" name="title"/>
</div>
{% csrf_token %}
<div class="form-group">
<textarea name="content"></textarea>
<script type = 'text/javascript'>
CKEDITOR.replace("content")
</script>
</div>
<button type="submit" class="btn btn-primary my-1" id='contact-button'>Post</button>
</form>
currently the add blog page
looks like this:目前,
add blog page
如下所示:
now I want a choose file
option after the content text area where the user can upload an image and then that image gets saved in the database, after which I can display the image in the blog section at frontend.现在我想要在内容文本区域之后
choose file
选项,用户可以在其中上传图像,然后将该图像保存在数据库中,之后我可以在前端的博客部分显示该图像。
pip install pillow
change <form>
to this:将
<form>
更改为:
<form method="post" enctype="multipart/form-data">
<input type='file' name='imagefile'>
require "multipart/form-data" to send image or file from form.需要“multipart/form-data”从表单发送图像或文件。
in settings.py add code:在 settings.py 中添加代码:
MEDIA_URL = '/media/'
in views.py if you are using function based view, do this:在 views.py 中,如果您使用基于函数的视图,请执行以下操作:
image = request.FILES.get('imagefile')
post = Post()
post.thumbnail=image
add other fields of the model.添加模型的其他字段。
save model by using post.save()
command.使用
post.save()
命令保存模型。
image.filename returns new file name of the image. image.filename 返回图像的新文件名。
it will directly save image in media/images/ folder它将直接将图像保存在 media/images/ 文件夹中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.