Django upload only csv file
<p>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.</p>

<p>myapp/views.py</p>

<pre><code>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'])
</code></pre>

<p>myapp/templates/myapp/index.html</p>

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

            &lt;p&gt;{{ form.docfile.label_tag }} {{ form.docfile.help_text }}&lt;/p&gt;

            &lt;p&gt;
                {{ form.docfile.errors }}
                {{ form.docfile }}
            &lt;/p&gt;

            &lt;p&gt;&lt;input type="submit" value="Upload"/&gt;&lt;/p&gt;
        &lt;/form&gt;
</code></pre>

<blockquote>
  <p>EDIT</p>
  
  <p>I could find a workaround by adding validate_file_extension as per the
  <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">django documentation</a></p>
  
  <p>myapp/forms.py</p>
</blockquote>

<pre><code>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])
</code></pre>

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

<pre><code>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])
</code></pre>

python django csv