Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

forms - Django ModelForm ImageField

I have a model and a form (forms.ModelForm) in which I have an ImageField. The model resembles:

class Business(models.Model):
    business_name = models.CharField(max_length=128)
    .
    .
    business_image = ImageField(
        max_length=128, 
        upload_to=upload_business_image_handler,
        height_field='business_image_height',
        width_field='business_image_width'
        )
    business_image_height = models.IntegerField(blank=True, null=True)
    business_image_width = models.IntegerField(blank=True, null=True)
    .
    .

The accompanying form:

class BusinessForm(forms.ModelForm):
    def __init__(self, data=None, files=None, branch_list = None, country_list = None, *args, **kwargs):
        super(BusinessForm, self).__init__(data, *args, **kwargs)
        # create the MultipleChoiceField choice_list based on language
        self.fields['branch'].choices = branch_list
        self.fields['country'].choices = country_list
        self.postdata = data
        self.files = files

    business_name = forms.CharField(widget=forms.TextInput(attrs={'size':'50', 'class': 'address'}), required=True)

    #business_image = forms.ImageField(widget=forms.ClearableFileInput())

The last line in the form is commented out because forms.ClearableFileInput() is the default widget for FileFields and ImageFields.

Now when this form is used to edit an existing record the image in the template is shown as follows:

Currently: <image_url>
Change: <browse_button>

I would like to change the text-labels 'Currently' and 'Change' and instead of showing the image_url I would like to show the image.

Of course I can copy and modify the code of 'class ClearableFileInput(FileInput)' found in 'site-packages/django/forms/widgets.py' but I am wondering if that's the way to accomplish this.

Any help or suggestion is appreciated.

Now I have looked at the code of 'class ClearableFileInput(FileInput)'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is my solution to the same problem.

from django.utils.safestring import mark_safe
from django.utils.html import escape, conditional_escape
from django.utils.encoding import force_unicode
from django.forms.widgets import ClearableFileInput, Input, CheckboxInput

class CustomClearableFileInput(ClearableFileInput):

    def render(self, name, value, attrs=None):
        substitutions = {
            #uncomment to get 'Currently'
            'initial_text': "", # self.initial_text, 
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
            }
        template = '%(input)s'
        substitutions['input'] = Input.render(self, name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = ('<img src="%s" alt="%s"/>'
                                        % (escape(value.url),
                                           escape(force_unicode(value))))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)

and then just use the extended widget:

business_image = forms.ImageField(widget=CustomClearableFileInput())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...