【问题标题】:Getting Image from image field to views.py model从图像字段获取图像到views.py模型
【发布时间】:2020-12-09 07:04:21
【问题描述】:

我正在用 Django 创建一个社交媒体网站。我有一个页面用于发布新帖子。它有一个带有文件字段的表单来上传图像。我想获取views.py 中的图像以保存在数据库中。在图像变量中,一个字符串与图像的名称一起保存。另外,我不想使用任何像 forms.py 这样的外部形式。在这里,我也尝试过 request.FILES["image"] 但它返回了一个空字典。

Views.py

def newpost(request):
if request.method == "POST":
    image = request.POST.get("image")
    caption = request.POST.get("caption")
    post = Post(Image=image,Caption=caption,Owner=request.user.username)
    post.save()
    return redirect("/")
return render(request,"newpost.html")

newpost.html

    {% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spark X- New Post</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}">

<script class="jsbin" src="{% static 'js/jquery.js' %}"></script>
    <link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon">
    <script>
             function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#blah')
                        .attr('src', e.target.result)
                };

                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</head>

<body>
    <div class="header">
        <span class="topband">
            <a href="/"><img src="{% static 'images/back icon.png'%}" class="topicon"></a>
        </span>
        <div class="logoholder">
            <p class="logotext">New Post</p>
        </div>
    </div>
    <div class="mainarea">
        <form action="" method="post">{% csrf_token %}
            <input type="file" name="image" id="image" accept="image/*" class="imageUpload" onchange="readURL(this);"/>
            <label for="image"><img src="{% static 'images/camera icon.png' %}" class="cameraIcon" id="blah"></label>
            
            <input type="text" name="caption" placeholder="Caption...   " class="caption">
            <button type="submit" class="submit">Post</button>
        </form>
    </div>
</body>

</html>

models.py

class Post(models.Model):
    Id = models.AutoField(primary_key=True)
    Image = models.ImageField(upload_to="Posts")
    date = models.DateTimeField(auto_now=True)
    Caption = models.TextField()

我们将非常感谢您的帮助。

【问题讨论】:

  • upload_to 是您的MEDIA_ROOT 下的目录。图像通常不存储在数据库中——而是您将它们上传到特定位置,当您请求时,数据库将保存有关要发送的图像的信息。如果您真的想将图像存储在数据库中,而不是磁盘上,我认为您需要BinaryField 而不是ImageField。我个人不会这样做。
  • 你试过 request.FILES.get("image") 吗??

标签: python html django


【解决方案1】:

我想通了。只需使用 request.FILES["image"] 并在表单中添加 enctype="multipart/form-data" 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2020-08-11
    • 2016-12-05
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多