0

I was trying to understand how to upload files using Django, so I used the example (latest version, upload is working):
https://github.com/axelpale/minimal-django-file-upload-example

I have a few Questions now:
How do I set a max file size? (I have checked the documentation of Django, but I don't get it)
Is there a way for me to read the file before the user uploads it?
(i.e a program that checks certain things and if they are ok, it can be uploaded)

Here is some code...
model.py:


class Document(models.Model):
    name= models.CharField(max_length=500)
    docfile= models.FileField(upload_to='documents/%Y/%m/%d', verbose_name="", validators=[validate_file_size])

    def __str__(self):
        return self.name + ": " + str(self.docfile)

validators.py:

def validate_file_size(value):
    filesize= value.size
    
    if filesize > 20971520:
        raise ValidationError("File too big")
    else:
        return value

views.py:

def uploadView(request):
    message = 'Upload your .csv-File'
    if request.method == 'POST':
        form = documentForm(request.POST, request.FILES)
        if form.is_valid():
            newDoc = Document(docfile=request.FILES['docfile'])
            newDoc.save()
            return redirect(uploadView)
        else:
            message = 'The form is not valid.'
    else:
        form = documentForm()
    
    documents = Document.objects.all()
    
    context = {'documents': documents, 'form': form, 'message': message}
    return render(request, 'upload.html', context)
  • Max file size: https://stackoverflow.com/questions/2472422/django-file-upload-size-limit. The same strategy can be applied to check (using custom validator will be preferable IMO), or you can create form with custom `clean()` (or even better `clean_field()` where `field` is field name) to inspect the file and deny upload if needed by raising/adding `ValidationError` (see https://docs.djangoproject.com/en/4.0/ref/forms/validation/) – STerliakov Feb 06 '22 at 16:40
  • I tried the first thing, but it is not working, I can still upload anything. I got the formatChecker.py and I changed the model as it is mentioned there. Do I have to call the clean() function somewhere? (would make sense, I just dont know where) – Sentenza_IV Feb 08 '22 at 11:57
  • No, form will call `clean` after all fields (see source code for `ModelForm.full_clean`). Please add validation code to the question (model definition, form code and any validators you have created), I'll try to help. I have used the first approach from that link in my own project before and it works (but later switched to validator for code consistency). – STerliakov Feb 08 '22 at 15:25
  • let me know if you need more of the code, I just added everything I thought is needed for the upload – Sentenza_IV Feb 08 '22 at 21:43
  • It looks fine now, I'll try to reproduce today. Please add form code as well and try setting size upper bound to 10 (to be sure that file is large enough). Why do you create `newDoc` instance manually instead of just saving form? Also, what is the exact problem you face? You submit the form with large file, but receive response for valid form and document is saved? – STerliakov Feb 09 '22 at 14:45

0 Answers0