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 1 year has passed since last update.

DjangoFormsのファイル指定でvalidationする方法

Last updated at Posted at 2022-08-15

【mui備忘録】
DjangoのFormsでCSVファイルのみを受け付ける方法。

1、CSVファイル以外のデータファイルが送られてきた際にValidationで通さない。
2、CSVファイル以外のデータファイルが送られてきた際にアラートを表示。

forms.py


from django import forms
from django.core.validators import FileExtensionValidator

class UploadForm(forms.Form):
    testfile = forms.FileField(
        validators=[FileExtensionValidator(['csv'])]#CSV指定
    )

index.html


{% if form.errors %}
    <ul>
    {% for error in form.testfile.errors %}
        <li>{{ error }}</li><!--form内にエラーがある際に表示させる-->
    {% endfor %}
    </ul>
{% endif %}

<form method="POST" class="form" enctype="multipart/form-data">
    <div>
        {{ form.testfile }}
    </div>
</form>

他にも、自作でValidationを充てることもできますので別の記事で載せたいと思います。

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?