Lohith
Lohith

Reputation: 934

Django upload only csv file

I am trying to import csv file i am able to import without any problem but the present functionality accepts all file types, i want the functionality to accept only csv file. below is the view.py and template file.

myapp/views.py

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            importing_file(request.FILES['docfile'])

myapp/templates/myapp/index.html

 <form action="{% url 'ml:list' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>

            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>

            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>

            <p><input type="submit" value="Upload"/></p>
        </form>

EDIT

I could find a workaround by adding validate_file_extension as per the django documentation

myapp/forms.py

def validate_file_extension(value):
        if not value.name.endswith('.csv'):
            raise forms.ValidationError("Only CSV file is accepted")
class DocumentForm(forms.Form): 
    docfile = forms.FileField(label='Select a file',validators=[validate_file_extension])

Upvotes: 2

Views: 4541

Answers (2)

Subin Shrestha
Subin Shrestha

Reputation: 1232

form widget to validate file extension

csv_file = forms.FileField(widget=forms.FileInput(attrs={'accept': ".csv"}))

Upvotes: 12

Lohith
Lohith

Reputation: 934

added code snippet to the forms.py file to validate file extension and now it is working fine.

def validate_file_extension(value):
        if not value.name.endswith('.csv'):
            raise forms.ValidationError("Only CSV file is accepted")
class DocumentForm(forms.Form): 
    docfile = forms.FileField(label='Select a file',validators=[validate_file_extension])

Upvotes: 3

Related Questions