如何在Django中保存调整大小的图像?

iszxjhcz  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(189)

我试着同时保存原始图像和调整大小的图像,但不知道Django会从哪个字段中了解到图像的大小,然后保存。

Models.py:

from django.db import models
from django_resized import ResizedImageField

class Post(models.Model):
    thumbnail = models.ImageField(upload_to ='uploads/posts/large/')
    thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/')

Forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['thumbnail','thumbnail_small']

Html:

<form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data">
    {% csrf_token %}
    <input type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg">
    <button type = "submit" class = "btn" name = "apost">Add Post</button>
</form>

所以,问题是,Django在哪里会明白它必须直接从<input name = "thumbnail">直接保存图像到thumbnail = models.ImageField(upload_to ='uploads/posts/large/')thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/')

vwkv1x7d

vwkv1x7d1#

您可以对PostForm使用save()方法,该方法继承自forms.ModelForm,然后为每个字段thumbnailthumbnail_small分别保存cleaned_data()

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['thumbnail']

    def save(self, commit=True):
        post = super().save(commit=False)

        image = self.cleaned_data['thumbnail']
        # Saves the image as is
        post.thumbnail = image
        # Saves the image resized, because the field does it automatically...
        post.thumbnail_small = image  

        if commit:
           post.save()

        return post

这个save()方法将在is_valid()True时运行。

相关问题