Home > Enterprise >  Empty request FILES in django
Empty request FILES in django

Time:07-29

I have a Django model containing a fileField and a ModelForm which requests the user upload a file. Yet no matter what I seem to do, the request.FILES returned by the server does not contain anything. Here is the model:

class RepoFile(models.Model):
    id = models.IntegerField(primary_key=True)
    repo = models.FileField(blank=False, null=True, upload_to="repos/")

The ModelForm:

class RepoUpload(forms.ModelForm):
    class Meta:
        model = RepoFile
        fields = ['repo']
        widgets = {
            'repo': ClearableFileInput(),
        }

And the HTML

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

Also here is the view that I am using:

    form = RepoUpload(request.FILES)
    if form.is_valid():
        print('this passed')
        form.save()

I noticed that no matter what file I upload in the "Choose File" section, the form.is_valid() returns false. If I just use HTML and the view to send request.FILES to a manually created object, len(request.FILES) returns 0. Does anyone know of a solution?

CodePudding user response:

you have a wrong init args in form, right is that:

form = RepoUpload(request.POST, request.FILES)

To avoid this error, is better to use:

form = RepoUpload(data=request.POST, files=request.FILES, )

additional kwargs for init:

data=None, 
files=None, 
auto_id='id_%s', 
prefix=None,
initial=None, 
error_class=ErrorList, 
label_suffix=None,
empty_permitted=False,
field_order=None,
use_required_attribute=None,
renderer=None

Read more here: https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form

  • Related