【问题标题】:Unable to Upload Image to Media Django无法将图像上传到媒体 Django
【发布时间】:2021-11-03 12:04:08
【问题描述】:

我在 Django 中上传图片时遇到了一些问题。提交表单后,图像 URL 已成功插入数据库,但没有为媒体文件创建图像。

请大家帮我找出问题所在。谢谢。

这里是代码。

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'static')
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR,'static/images/')

models.py

class Image(models.Model):
   img = models.ImageField(upload_to='testing')

views.py

def goProfile(request):
 if request.method == "POST":
    image = Image(
        img = request.POST.get('imgTest')
    )
    image.save()

 return render(request,'profile.html')

profile.html

        <form action="" method="post">
          {% csrf_token %}
          <input type="file" name="imgTest" id="imgTest">
          <input type="submit" value="submit">
        </form>

【问题讨论】:

  • 能否分享一下错误信息?
  • @Sabil 现在问题解决了。解决方案在下面。另外,感谢您尝试帮助我:)

标签: python django django-models file-upload


【解决方案1】:

在你的表单中试试这个

<form action="" method="post" enctype="multipart/form-data">
          {% csrf_token %}
          <input type="file" name="imgTest" id="imgTest">
          <input type="submit" value="submit">
        </form>

也在你的视图中请求.FILES

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2023-02-11
    • 1970-01-01
    • 2019-07-01
    • 2021-11-03
    • 2015-10-04
    • 1970-01-01
    • 2012-10-05
    • 2021-05-11
    相关资源
    最近更新 更多