我试着同时保存原始图像和调整大小的图像,但不知道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/')
?
1条答案
按热度按时间vwkv1x7d1#
您可以对
PostForm
使用save()
方法,该方法继承自forms.ModelForm
,然后为每个字段thumbnail
和thumbnail_small
分别保存cleaned_data()
。这个
save()
方法将在is_valid()
是True
时运行。