11

我在文档中找不到这个,但认为它一定是可能的。我说的是 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 }}似乎不起作用。接下来我想到的是编写一个自定义小部件。这将完全不利于我删除尽可能多的自定义代码的努力。

任何想法在这种情况下最简单的事情是什么?

4

1 回答 1

25

首先,widgets.py在应用程序中创建一个文件。对于我的示例,我将为您创建一个AdminImageWidget可扩展的类AdminFileWidget。本质上,我想要一个图像上传字段,在<img src="" />标签中显示当前上传的图像,而不仅仅是输出文件的路径。

将以下类放入您的widgets.py文件中:

from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
import os
import Image

class AdminImageWidget(AdminFileWidget):
    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):

            image_url = value.url
            file_name=str(value)

            # defining the size
            size='100x100'
            x, y = [int(x) for x in size.split('x')]
            try :
                # defining the filename and the miniature filename
                filehead, filetail  = os.path.split(value.path)
                basename, format        = os.path.splitext(filetail)
                miniature                   = basename + '_' + size + format
                filename                        = value.path
                miniature_filename  = os.path.join(filehead, miniature)
                filehead, filetail  = os.path.split(value.url)
                miniature_url           = filehead + '/' + miniature

                # make sure that the thumbnail is a version of the current original sized image
                if os.path.exists(miniature_filename) and os.path.getmtime(filename) > os.path.getmtime(miniature_filename):
                    os.unlink(miniature_filename)

                # if the image wasn't already resized, resize it
                if not os.path.exists(miniature_filename):
                    image = Image.open(filename)
                    image.thumbnail([x, y], Image.ANTIALIAS)
                    try:
                        image.save(miniature_filename, image.format, quality=100, optimize=1)
                    except:
                        image.save(miniature_filename, image.format, quality=100)

                output.append(u' <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s ' % \
                (miniature_url, miniature_url, miniature_filename, _('Change:')))
            except:
                pass
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

好的,那么这里发生了什么?

  1. 我导入了一个现有的小部件(您可能从头开始,但如果这是您开始的,应该可以扩展 ClearableFileInput)
  2. 我只想更改小部件的输出/呈现,而不是底层逻辑。所以,我覆盖了小部件的render功能。
  3. 在渲染函数中,我将我想要的输出构建为一个数组output = [],您不必这样做,但它可以节省一些连接。3条关键线:
    • output.append(u' <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s ' % (miniature_url, miniature_url, miniature_filename, _('Change:')))在输出中添加 img 标签
    • output.append(super(AdminFileWidget, self).render(name, value, attrs))将父级的输出添加到我的小部件
    • return mark_safe(u''.join(output))用空字符串加入我的输出数组,并在显示前避免它转义

我该如何使用它?

class SomeModelForm(forms.ModelForm):
    """Author Form"""
    photo = forms.ImageField(
        widget = AdminImageWidget()
    )

    class Meta:
        model = SomeModel

或者

class SomeModelForm(forms.ModelForm):
    """Author Form"""
    class Meta:
        model = SomeModel
        widgets = {'photo' : AdminImageWidget(),}

这给了我们:

管理员截图

于 2012-04-24T18:03:21.567 回答