前奏曲:
ImageFieldを表示する最も簡単な方法を次に示します。template.html
フォームに 10 個のフィールドがあり、それが imageField であるかどうかを確認して別の方法で表示するためだけに、それらすべてを反復処理したくないとします。フォームやウィジェットなどで処理したい。したがって、次のように 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
フォーム.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
メソッドがフォームではなくモデルの一部である必要があるのはなぜですか? モデルは、フォームを介してユーザーにデータを提示する方法ではなく、データベース内でデータを保持する方法を記述します。これはフォームの一部である必要がありますね。間違っていたら訂正してください。問題を解決するにはどうすればよいですか? どんな助けでも大歓迎です!