Preston
Preston

Reputation: 8187

request.FILES empty, though file is present in request

Following the example on the django website I'm trying to upload a file, perform checks on the contents, then feedback to the user and store the file contents.

However, I'm having trouble with the request.FILES which is always empty. My code is as follows (note the output after the print statements):

**forms.py**
class UploadFileForm(forms.Form):
    data_import = forms.FileField()

    class Meta:
        model = Recipe
        fields = ('data_import',)


**view**
def recipes_list(request):
    template = 'recipes/recipes_list.html'

    if request.method == 'GET':
        user = request.user
        queryset = Recipe.objects.filter(user=user)
        form = UploadFileForm()
        return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form})

    elif request.method == 'POST':
        print(request.FILES) # <MultiValueDict: {}>
        print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}>
        form = UploadFileForm(request.POST, request.POST.data_import)

        if form.is_valid():
            return HttpResponseRedirect(template)
        else:
            print(form.errors)


**template**
<form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">submit</button>
</form>  

The error I'm getting is:

<ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

But i can see that the file is uploaded, and is in the request.POST.get('data_import').

I would like to run validation on the form, but I can't do this if request.FILES is empty.

I'm clearly doing something wrong, can someone please point me in the right direction?

Upvotes: 0

Views: 215

Answers (1)

Exprator
Exprator

Reputation: 27503

<form method="post" enctype= multipart/form-data>
    {% csrf_token %}
    {{ form }}
    <button type="submit">submit</button>
</form> 

change your form to the upper one

Upvotes: 1

Related Questions