title: How to secure files upload using django
body: <p>The code below works very well by uploading files to server. </p>
  
  <p>please how do I validate and secure the files upload by checking the files Size (Eg. 2mb), file extension name,
  Files Mimetype and other checking to ensure that only image like .jpg,.gif,.png are uploaded and not virus.</p>
  
  <p><strong>model.py</strong></p>
  
  <pre><code>from django.db import models
  
  # Create your models here.
  class File(models.Model):
      file = models.FileField()
  
      def __str__(self):
          return self.file.name
  </code></pre>
  
  <p><strong>View.py</strong></p>
  
  <pre><code>from django.shortcuts import render
  from django.core.files.storage import FileSystemStorage
  from .models import File
  import os, datetime
  
  from .forms import uploadForm
  
  # Create your views here.
  
  def index(request):
      if request.method == 'POST' and request.FILES:
  
          form = uploadForm(request.POST,request.FILES)
  
  
          if form.is_valid():
              file = request.FILES['file']
              # process the data in form.cleaned_data as required
              file_object = form.cleaned_data['file']
              extension = os.path.splitext(file_object.name)[1]
              rename = datetime.datetime.now().strftime("%Y_%m_%d %H_%M_%S") + extension
              fss = FileSystemStorage()
              filename = fss.save(rename, file_object)
              file = File(file=rename)
              file.save()
              upload_file_path = fss.path(filename)
  
              return render(request, 'file/index.html', {
              'upload_file_path': upload_file_path})
              print('uploaded')
          else:
              print("Not Valid")
  
      else:
          return render(request, 'file/index.html')
  </code></pre>
  
  <p><strong>forms.py</strong></p>
  
  <pre><code>from django import forms
  
  class uploadForm(forms.Form):
      #file = forms.CharField()
       file = forms.FileField()
  </code></pre>