Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7851545
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T19:12:33+00:00 2026-06-02T19:12:33+00:00

I couldn’t find this in the docs, but think it must be possible. I’m

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T19:12:34+00:00Added an answer on June 2, 2026 at 7:12 pm

    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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Couldn't find an answer to this question. It must be obvious, but still. I
I couldn't find this in the docs , but how am I meant to
I couldn't really find this in Rails documentation but it seems like 'mattr_accessor' is
couldn't find a similar topic but this may boil down to not knowing how
Couldn't find this directly on the NHAML project page, so i was wondering if
Couldn't think of better phrasing for this question, but basically I want to store
Couldn't find better title but i need a Regex to extract link from sample
I couldn't find this anywhere on the web so I'm most likely is not
I couldn't find a suitable title for this. I'm going to express my query
Couldn't find a better place to ask this so I hope you guys can

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.