0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoで画像がアップロードされていない時とされているときの条件分岐

Posted at

書いた理由

Djangoでメッセージアプリを作っているとき、アイコン画像の表示に苦労したため。

例について

ユーザーがアイコン画像を設定しているときはその画像を表示し、アイコン画像が設定されていない時はデフォルトの画像を表示するようにした。
以下、変数の説明。
friend:ユーザー一人一人の名前やアイコン画像などの情報が格納されているUserオブジェクトのインスタンス。
friend.img:friendのうち、そのユーザーの画像のデータ。
person.png:デフォルトのアイコン画像。

やり方

index.html
{% if friend.img %}
<img src="/media/{{ friend.img }}" alt="icon" width="30vw" height="30vh">
{% else %}
<img src="/media/img/upload/person.png" alt="icon" width="30vw" height="30vw">
{% endif %}

if文でfriend.imgとするだけで、「画像がアップロードされているときは以下の処理を実行する」という意味になるらしい。
{% if friend.img != None %}とか試したけど、そんなことをする必要はないようです。

間違って理解している部分があったらご指摘お願いします!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?