如何判断用户是否更改了 django ModelForm 中的文件
How to tell if user changed file in django ModelForm
我有一个带有图像字段的 django ModelForm
。我想在用户提交表单时调整图像大小,但前提是他们上传了新图像。我的代码如下所示:
class EditProfileForm(forms.ModelForm):
class Meta:
model = Person
fields = ['picture', '...']
def clean_picture(self):
picture = self.cleaned_data['picture']
if picture.file: #This isn't right though
#resize it
return picture
然而,如果正在编辑的模型包含一个文件,似乎 picture.file
总是存在。我知道我可以在视图中检查 request.FILES
,但这很不雅观。有没有更好的方法?
通常,您可以使用 self.changed_data
来执行此操作,其中 returns 值已更改的字段的名称列表。 FileField
是否有任何特别之处会干扰我不知道。
在 js 中,
- 在JS中,设置一个全局变量file_changed = 0。
- HTML 输入标签 < input ng-model="avatar" type="file" onchange="ChangeFile()">
- 假设 ChangeFile() 将提供要上传的文件的小预览
- 在函数 ChangeFile 中设置 file_changed=1 选择文件后。
我有一个带有图像字段的 django ModelForm
。我想在用户提交表单时调整图像大小,但前提是他们上传了新图像。我的代码如下所示:
class EditProfileForm(forms.ModelForm):
class Meta:
model = Person
fields = ['picture', '...']
def clean_picture(self):
picture = self.cleaned_data['picture']
if picture.file: #This isn't right though
#resize it
return picture
然而,如果正在编辑的模型包含一个文件,似乎 picture.file
总是存在。我知道我可以在视图中检查 request.FILES
,但这很不雅观。有没有更好的方法?
通常,您可以使用 self.changed_data
来执行此操作,其中 returns 值已更改的字段的名称列表。 FileField
是否有任何特别之处会干扰我不知道。
在 js 中,
- 在JS中,设置一个全局变量file_changed = 0。
- HTML 输入标签 < input ng-model="avatar" type="file" onchange="ChangeFile()">
- 假设 ChangeFile() 将提供要上传的文件的小预览
- 在函数 ChangeFile 中设置 file_changed=1 选择文件后。