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

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

问题描述

前奏:

此处是显示ImageField的最简单方法.假设我的表单中有10个字段,并且我不想在template.html中遍历所有字段,只是为了检查它是否是imageField并以其他方式显示它.我想通过表单或小部件或之类的东西来处理它.因此,我希望将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>

并将image_tag方法添加到 models.py :

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)

我得到一个错误,说Unknown field(s) (image_tag) specified for UserProfile足够.

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天全站免登陆