11

I couldn't find this in the docs, but think it must be possible. I'm talking specifically of the ClearableFileInput widget. From a project in django 1.2.6 i have this form:

# 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',)

which i then rendered using this template code:

<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>

As Django 1.3.1 now uses ClearableFileInput as the default widget, i'm pretty sure i can skip the 16 lines of my form.save and just shorten the form code like so:

# 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',)

That would give me the good feeling that i have less customized formcode, and can rely on the Django builtins.

I would, of course, like to keep the html-output the same as before. When just use the existing template code, such things like "Currently: somefilename.png" pop up at places where i do not want them.

Splitting the formfield further, like {{ upload_form.image.file }} does not seem to work. The next thing coming to my mind was to write a custom widget. Which would work exactly against my efforts to remove as many customized code as possible.

Any ideas what would be the most simple thing to do in this scenario?

5
  • short answer: STEP 1: extend the widget class STEP 2: override the widget for your field Note: you want to use the subclassed widget that you created in step 1 in the django form's __init__ method. If you need examples, let me know and I'll hit it this afternoon. Commented Apr 5, 2012 at 13:46
  • The latest i was thinking about is to just override the template used by the widget. Would appreciate you tuning in this afternoon (you are obviously on a different continent than i am, as here it is allready 16:15 :D ) Commented Apr 5, 2012 at 14:18
  • yea when i get off work, ill shoot you an example. ~5 or so hours Commented Apr 5, 2012 at 15:54
  • @Francis: You still didn't get off work? Wow, hope they pay you well. :D - seriously, i would very much appreciate if you could do an answer to this question, as i ran into the same problem again. Commented Apr 24, 2012 at 7:35
  • ha, sorry I completely forgot about this. I'm doing it right now Commented Apr 24, 2012 at 17:42

1 Answer 1

25

Firstly, create a widgets.py file in an app. For my example, I'll be making you an AdminImageWidget class that extends AdminFileWidget. Essentially, I want a image upload field that shows the currently uploaded image in an <img src="" /> tag instead of just outputting the file's path.

Put the following class in your widgets.py file:

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))

Ok, so what's happening here?

  1. I import an existing widget (you may be starting from scratch, but should probably be able to extend ClearableFileInput if that's what you are starting with)
  2. I only want to change the output/presentation of the widget, not the underlying logic. So, I override the widget's render function.
  3. in the render function I build the output I want as an array output = [] you don't have to do this, but it saves some concatenation. 3 key lines:
    • output.append(u' <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s ' % (miniature_url, miniature_url, miniature_filename, _('Change:'))) Adds an img tag to the output
    • output.append(super(AdminFileWidget, self).render(name, value, attrs)) adds the parent's output to my widget
    • return mark_safe(u''.join(output)) joins my output array with empty strings AND exempts it from escaping before display

How do I use this?

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

    class Meta:
        model = SomeModel

OR

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

Which gives us:

admin screenshot

Sign up to request clarification or add additional context in comments.

3 Comments

Ugh, nearly two years later and this is still getting up-votes, please don't implement this as-is with its custom resizing scripts. Use SORL or something like it. Also, please note that this doesn't work with django storages, it just assumes you are writing/reading on the filesystem.
SORL? The Auto Parts Company?
In case anyone is using the approach above or similar with Django >= 1.11: The overridden render function now takes an additional renderer keyword argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.