【发布时间】:2015-04-30 03:15:20
【问题描述】:
前奏:
Here 是显示 ImageField 的最简单方法。假设我的表单中有 10 个字段,我不想在 template.html 中遍历所有字段,只是为了检查它是否是一个 imageField 并以不同的方式显示它。我想通过表单或小部件或this 之类的东西来处理它。所以我想要离开 template.html,如下所示。
template.html
<table>
{{ form.as_table }}
</table>
并在 models.py 中添加一个 image_tag 方法:
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 这很公平。
我也尝试将它放在readonly_fields 中,但它们不会以某种方式显示。我必须创建list_view 吗?如果是,应该在哪里?
我在这里想念什么?为什么image_tag 方法应该是模型而不是表单的一部分?模型描述了数据应该如何保存在数据库中,而不是它应该如何通过表单呈现给用户。这应该是表单的一部分,不是吗?如果我错了,请纠正我。我该如何解决这个问题?任何帮助将不胜感激!
【问题讨论】:
-
您不能在 ModelForm 的字段列表中使用方法。我没有尝试过,但您可以编写一个自定义小部件并将其设置为 ModelForm 中照片字段的默认小部件。
-
也许用@property 在你的模型中装饰
image_tag方法会对你有所帮助。
标签: django django-models django-forms django-uploads