我在文档中找不到这个,但认为它一定是可能的。我说的是 ClearableFileInput 小部件。从 django 1.2.6 的一个项目中,我有这种形式:
# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
"""
simple form for uploading an image. only a filefield is provided
"""
delete = forms.BooleanField(required=False,widget=forms.CheckboxInput())
def save(self):
# some stuff here to check if "delete" is checked
# and then delete the file
# 8 lines
def is_valid(self):
# some more stuff here to make the form valid
# allthough the file input field is empty
# another 8 lines
class Meta:
model = SocialUserProfile
fields = ('image',)
然后我使用此模板代码呈现:
<form action="/profile/edit/" method="post" enctype="multipart/form-data">
Delete your image:
<label> {{ upload_form.delete }} Ok, delete </label>
<button name="delete_image" type="submit" value="Save">Delete Image</button>
Or upload a new image:
{{ upload_form.image }}
<button name="upload_image" type="submit" value="Save">Start Upload</button>
{% csrf_token %}
</form>
由于 Django 1.3.1 现在使用 ClearableFileInput 作为默认小部件,我很确定我可以跳过 form.save 的 16 行,并像这样缩短表单代码:
# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
"""
simple form for uploading an image. only a filefield is provided
"""
class Meta:
model = SocialUserProfile
fields = ('image',)
这会给我一种很好的感觉,即我的自定义表单代码较少,并且可以依赖 Django 内置函数。
当然,我希望保持 html 输出与以前相同。当只使用现有的模板代码时,诸如“当前:somefilename.png”之类的东西会在我不想要它们的地方弹出。
进一步拆分表单域,{{ upload_form.image.file }}
似乎不起作用。接下来我想到的是编写一个自定义小部件。这将完全不利于我删除尽可能多的自定义代码的努力。
任何想法在这种情况下最简单的事情是什么?