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?

【Django】ファイルサイズのKB表示

Last updated at Posted at 2025-05-16

やりたいこと

アップロードしたファイルのサイズをKB単位で表示したい。

イメージ

image.png

models.py

models.py
class UploadFile(models.Model):
    title = models.CharField(max_length=50)
    file = models.FileField(upload_to='uploads/')

    # ファイル名を取得
    @property
    def filename(self):
        return self.file.name.split("/")[-1]  # uploads/を除くファイル名だけ取得

+   # ファイルサイズを取得
+   @property
+   def file_size(self):
+       return self.file.size // 1024  # KB単位で取得 
  • @property を使うとfile_sizeで呼び出せる
  • ファイルサイズはbyte単位で取得されるので、// 1024 で割る
  • 割り算の結果を整数で取り出している

detail.html

detail.html
    <ul class="list-group list-group-flush">
        {% for file in object.uploaded_files.all %}
            <li class="list-group-item">
                <a href="{{ file.file.url }}">{{ file.filename }}</a> <small>{{ file.uploaded_at }}</small>
+               <p class="text-end blockquote-footer mb-0">ファイルサイズ:{{ file.file_size }} KB </p>
            </li>
        {% empty %}
            <li class="list-group-item">
                アップロードされたファイルはありません。
            </li>
        {% endfor %}
    </ul>
  • 装飾にはBootstrapを利用しています
  • MB単位にしたい場合はさらに // 1024
  • 小数点で表示する場合は / 1024
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?