2

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])
2
  • get the file mime type and check if it is csv. Commented Sep 3, 2016 at 6:26
  • this link provides a workaround stackoverflow.com/a/8826854/4915288 Commented Sep 3, 2016 at 6:45

2 Answers 2

12

form widget to validate file extension

csv_file = forms.FileField(widget=forms.FileInput(attrs={'accept': ".csv"}))
Sign up to request clarification or add additional context in comments.

Comments

3

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.