【问题标题】:Django ModelForm ImageFieldDjango ModelForm ImageField
【发布时间】:2012-06-05 00:46:14
【问题描述】:

我有一个模型和一个表单 (forms.ModelForm),其中有一个 ImageField。该模型类似于:

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

随附表格:

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

表单中的最后一行被注释掉,因为 forms.ClearableFileInput() 是 FileFields 和 ImageFields 的默认小部件。

现在,当使用此表单编辑现有记录时,模板中的图像如下所示:

Currently: <image_url>
Change: <browse_button>

我想更改文本标签“当前”和“更改”,而不是显示 image_url 我想显示图像。

当然,我可以复制和修改在“site-packages/django/forms/widgets.py”中找到的“class ClearableFileInput(FileInput)”的代码,但我想知道这是否是实现此目的的方法。

感谢任何帮助或建议。

现在我查看了'class ClearableFileInput(FileInput)'的代码

【问题讨论】:

    标签: django forms


    【解决方案1】:

    我会将其放入模板表单中

    {% if business.business_image %}
       <img src="{{ business.business_image.url }}" title="{{ business.business_name}}" />
    {% endif %}
    

    【讨论】:

    • 是的,它会在模板中显示图像,但我提到的 2 个项目,当前: 和更改: 仍将在模板中。
    【解决方案2】:

    这是我的 imageInput 版本,它显示图像并且不允许清除图像

    只需在表单类中指定该字段具有widget=NonClearableImageInput()

    from django.forms.widgets import FileInput
    from django.utils.html import conditional_escape
    from django.utils.safestring import mark_safe
    
    class NonClearableImageInput(FileInput):
        def render(self, name, value, attrs=None):
            template = '%(input)s'
            data = {'input': None, 'url': None}
            data['input'] = super(NonClearableImageInput, self).render(name, value, attrs)
    
            if hasattr(value, 'url'):
                data['url'] = conditional_escape(value.url)
                template = '%(input)s <img src="%(url)s">'
    
            return mark_safe(template % data)
    

    【讨论】:

    • 你好,我用过这个版本。但我有一个问题。我正在手动呈现表单。我正在根据需要获得旧照片。在该图片上方添​​加我得到一个按钮“选择文件”和一个帮助文本“未选择文件”。有什么方法可以将文本更改为“上传照片”并删除帮助文本。我还将按钮移动到显示的图片下方。有什么办法吗?
    【解决方案3】:

    这是我对同一问题的解决方案。

    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)
    

    然后只需使用扩展小部件:

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

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 2010-10-15
      • 2015-05-24
      • 2013-06-19
      • 1970-01-01
      • 2013-06-07
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多