简体   繁体   English

如何在django数据库中保存图像?

[英]How to save image in django database?

I have a newclaim form which allows user to upload a picture我有一个新的索赔表,允许用户上传图片

The current problem I faced is whenever I try to upload a new picture, it is not stored on my database (which is my models.py)我目前面临的问题是,每当我尝试上传新图片时,它都没有存储在我的数据库中(这是我的 models.py)

How do I solve this?我该如何解决这个问题?

This is my views.py这是我的views.py

    def NewClaim(request):
  context = initialize_context(request)
  user = context['user']
  form = ClaimForm()
  lastimage= Image.objects.last()
  imagefile= lastimage.imagefile

  if request.method == 'POST':
      form = ClaimForm(request.POST)
      if form.is_valid():
        form.save()
        return redirect ('ViewClaim')

  return render(request, "User/NewClaim.html", {'user':user, 'form':form, 'date': x})


**This is my newclaim.html**

    <form action="/newclaim/" method="post" enctype="multipart/form-data">
           <div>
                    <input id="receipt" type="file" name="receipt_field" style="display: none; visibility: none;">
          </div>
    </form>

This is my saveclaimform models这是我的 saveclaimform 模型

class SaveClaimForm(models.Model):
    receipt = models.FileField(upload_to='receipts/%Y/%m/%D', validators=[FileExtensionValidator(allowed_extensions=['jpg','png'])])

You might want to have a look at this article .您可能想看看这篇文章 Make sure you've modified the settings.py file and the urls.py file to include the info about where you're going to be storing the images.确保您已修改 settings.py 文件和 urls.py 文件以包含有关您将存储图像的位置的信息。

Images won't be stored in the database, but rather, they'll be stored in a folder that you specify.图像不会存储在数据库中,而是存储在您指定的文件夹中。 You can then generate a path for that image, which can and will be stored in the database.然后,您可以为该图像生成一个路径,该路径可以并且将存储在数据库中。

  form = ClaimForm(request.POST, request.FILES)
  if form.is_valid():
     now take file input here
     and process form as usual

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM