Django 表单不更新文件/图像

问题描述 投票:0回答:1

我已经构建了一个可以很好地创建新对象的表单。我也可以很好地更新所有文本。它不允许我更新图像。 我正在使用 Crispy Forms 来构建表单。 我哪里搞错了?

我的模型看起来像这样:

class Bottle(models.Model):
    class displaySorting(models.IntegerChoices):
        Lighthouse = 1
        Regular = 2

    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    sorting = models.IntegerField(choices = displaySorting.choices,verbose_name='Sort order')
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    bottle_size = models.IntegerField(validators=[MaxValueValidator(9999)])
    info = HTMLField()
    tasting_notes = HTMLField()
    abv = models.DecimalField(max_digits=3, decimal_places=1, verbose_name='Alcohol %')
    image = ResizedImageField(size=[1000,1000], upload_to=image_upload_handler)
    thumbnail = models.ImageField(upload_to='thumbnails')
    shop_link = models.URLField()
    consumer_shop_link = models.URLField()
    website_link = models.URLField()

  def save(self, *args, **kwargs):
        self.slug = slugify(f"{self.brand}-{self.name}")
        output_size = (300, 169)
        output_thumb = BytesIO()

        img = Image.open(self.image)
        img_name = self.image.name.split('.')[0]

        if img.height > 300 or img.width > 300:
            img.thumbnail(output_size)
            img.save(output_thumb,format='JPEG',quality=90)

        self.thumbnail = InMemoryUploadedFile(output_thumb, 'ImageField', f"{self.brand}-{img_name}_thumb.jpg", 'image/jpeg', sys.getsizeof(output_thumb), None)

        super(Bottle, self).save()

我的观点是这样的:

@login_required
def bottle_update_view(request, id=None):
    object = get_object_or_404(Bottle, id=id)
    form = BottleForm(request.POST or None, instance=object)

    context = {
        'form':form,
        'object':object
    }

    if form.is_valid():
        form.save()
        context['message'] = 'Data saved'

    return render(request,'Academy/bottle_crud.html',context)

最后我的模板是这样的:

    {% block content %}

<div class='container'> 
    <div class='row form'>
        <h1 class='text-center my-5'>Add & Update bottle</h1>
       {% if message %}
            <div> 
                <div><h2>{{message}}</h2></div>
                <div><a href="{{object.get_bottle_link}}"><h2 class='link'>Check bottle</h2></a></div>
            </div>
        
       {% endif %}

       <form enctype='multipart/form-data' method='POST'>
        {% crispy form %}
        </form>
    </div>
</div>



{% endblock content %} 

编辑: 我已将 request.FILES 添加到如下形式:

form = BottleForm(request.POST or None, request.FILES, instance=object)

但是表单将不再加载任何要更新的信息,它现在只是一个空表单。

django django-models django-views django-forms django-crispy-forms
1个回答
0
投票

img.save(output_thumb,format='JPEG',quality=90)

    self.thumbnail = InMemoryUploadedFile(output_thumb, 'ImageField', f"{self.brand}-{img_name}_thumb.jpg", 'image/jpeg', sys.getsizeof(output_thumb), None)

您指定了 jpeg 作为图像类型,并且您正在尝试上传 jpeg 以外的文件。

© www.soinside.com 2019 - 2024. All rights reserved.