简体   繁体   中英

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)

How do I solve this?

This is my 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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