首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django ModelForm ImageField

Django ModelForm ImageField
EN

Stack Overflow用户
提问于 2012-05-31 02:27:58
回答 3查看 9.1K关注 0票数 4

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

代码语言:javascript
复制
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)
    .
    .

随附的表格:

代码语言:javascript
复制
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的默认小部件。

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

代码语言:javascript
复制
Currently: <image_url>
Change: <browse_button>

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

当然,我可以复制并修改‘site-package/django/forms/widgets.py’中的‘类ClearableFileInput(FileInput)’代码,但我想知道这是否是实现此目的的方法。

任何帮助或建议都是非常感谢的。

现在,我已经查看了“ClearableFileInput(FileInput)类”的代码。

EN

回答 3

Stack Overflow用户

发布于 2012-06-17 06:58:10

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

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
business_image = forms.ImageField(widget=CustomClearableFileInput())
票数 4
EN

Stack Overflow用户

发布于 2012-05-31 02:38:38

我把这个放到模板表单中

代码语言:javascript
复制
{% if business.business_image %}
   <img src="{{ business.business_image.url }}" title="{{ business.business_name}}" />
{% endif %}
票数 1
EN

Stack Overflow用户

发布于 2015-08-21 16:48:19

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

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

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10822111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档