Django ImageField无法渲染ClearableFileInput

时间:2013-11-24 20:08:05

标签: python django widget

开始把我的头撞到墙上......也许我错过了一些简单的事情。

models.py

class GFImage(models.Model):
    image = models.ImageField(upload_to = 'uploads', null=True, blank=True)

views.py

def addImage(request):
errors = []
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        urlRedirect = "/home"
        return redirect(urlRedirect)
else:
    form = ImageForm()
return render(request, "/add_image.html", {'form': form})

forms.py

class ImageForm(ModelForm):
    class Meta:
        model = GFImage

add_image.html

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <input type = "submit" value = "Submit">

</form>

无论我做什么,我的表单都不会使用ClearableFileInput小部件。它应该自动默认,但即使在表单的META中分配它也行不通。还有什么可以阻止Django使用可清除小部件?

1 个答案:

答案 0 :(得分:1)

ClearableFileInput只会在选择初始文件时显示清除复选框。查看您的表单,它看起来像一个没有初始数据的新表单,因此不会显示该复选框。

def render(self, name, value, attrs=None):
    .. snip ..
    if value and hasattr(value, "url"):
        template = self.template_with_initial
        substitutions['initial'] = format_html(self.url_markup_template,

https://github.com/django/django/blob/5fda9c9810dfdf36b557e10d0d76775a72b0e0c6/django/forms/widgets.py#L372