通过表单显示来自 ImageField 的图像 [英] Display image from ImageField by means of form

查看:19
本文介绍了通过表单显示来自 ImageField 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前奏:

这里是显示 ImageField 的最简单方法.假设我的表单中有 10 个字段,我不想在 template.html 中遍历所有字段,只是为了检查它是否是一个 imageField 并以不同的方式显示它.我想通过表单或小部件或类似 this 的方式处理它.所以我想要离开 template.html 如下所示.

Here's the simpliest way to display an ImageField. Lets assume I have 10 fields in my form and I don't wanna iterate over all of them in template.html just to check if it's an imageField and display it in a different way. I want to handle it via form or widget or something like this. So I want the leave template.html as it's bellow.

template.html

<table>
    {{ form.as_table }}
</table>

并在 models.py 中添加一个 image_tag 方法:

And add to models.py an image_tag method:

class UserProfile(Model):
  photo = ImageField(upload_to=PHOTO_DIRECTORY)
  contacts = TextField(null=True)
  ... others

  def image_tag(self):
    return u'<img src="%s" />' % self.photo.url

  image_tag.short_description = 'Image'
  image_tag.allow_tags = True

forms.py:

class UserProfileForm(forms.ModelForm):

  class Meta:
    model = UserProfile
    fields = ('contacts', 'photo', 'image_tag', ...others)

我收到一个错误,为 UserProfile 指定的未知字段 (image_tag) 是公平的.

I get an error that Unknown field(s) (image_tag) specified for UserProfile which is fair enought.

我也尝试将它放在 readonly_fields 中,但它们不以某种方式显示.我是否必须创建 list_view?如果是,它应该在哪里?

I also tried to place it in readonly_fields but they don't display somehow. Do I have to create list_view? If yes where should it be?

我在这里想念什么?为什么 image_tag 方法应该是模型的一部分而不是表单?模型描述了数据应该如何保存在数据库中,而不是它应该如何通过表单呈现给用户.这应该是表格的一部分,不是吗?如果我错了,请纠正我.我该如何解决这个问题?任何帮助将不胜感激!

What do I miss here? Why the image_tag method should be a part of model instead of form? Model describes how data should persists in the database, not how it should present to user via form. This should be a part of form, shouldn't it?. Correct me please if I'm wrong. How do I solve the issue? Any help would be greatly appreciated!

推荐答案

正如 Selcuk 提到的最简单的解决方案是创建我自己的小部件.

As Selcuk mentioned the simplest solution was to create my own widget.

from string import Template
from django.utils.safestring import mark_safe
from django.forms import ImageField

class PictureWidget(forms.widgets.Widget):
    def render(self, name, value, attrs=None, **kwargs):
        html =  Template("""<img src="$link"/>""")
        return mark_safe(html.substitute(link=value))

class UserProfileForm(forms.ModelForm):
    photo = ImageField(widget=PictureWidget)

这篇关于通过表单显示来自 ImageField 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆