pilgrim
pilgrim

Reputation: 11

How to upload file to server with django?

I've found this very simple code for my problem but I've tried to repeat it in my project and there was no result. I think I do everything correctly but result is bad.

I do so:

forms.py

class UploadFileForm(forms.Form):
    docfile = forms.FileField(
        label='select file pls'
    )

views.py

class CabinetView(TemplateView, UploadFileForm):
    template_name = 'cabinet.html'

def get_context_data(self, **kwargs):
    if not self.request.user.is_authenticated() or self.request.user.is_anonymous():
        raise ValueError('You are not log in. Please do it.')
    context = super(CabinetView, self).get_context_data(**kwargs)
    if self.request.user.first_name:
        context['current_user'] = self.request.user.first_name
    else:
        context['current_user'] = self.request.user

    return context

def post(self, request):
    if self.request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            my_file = self.request.FILES['docfile']
            print my_file.name
        else:
            print 'invalid'
    return render(self.request, 'cabinet.html', {'form': form})

html template:

<body>
<form method="post">{% csrf_token %}
    {{ form }}
    <p><input type="submit" value="Upload"/></p>
</form>
</body>

I'm waiting for uploading file, but when I'm trying to do it (I have button "browse..." and I try to push it after choosing file) terminal says:

POST /cabinet/ HTTP/1.1 200 5740

form: <tr><th><label for="id_docfile">select file pls:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_docfile" name="docfile" type="file" /></td></tr>

invalid

So, form is invalid. I can't understand why.

Sorry for very simple question. If there are any problems im my questions I'm sorry. It's my first question at stackoverflow.

My settings are: Python 2.7 Django 1.9.7 Ubuntu 14.04

Upvotes: 1

Views: 1053

Answers (1)

rafalmp
rafalmp

Reputation: 4068

Replace

my_file = self.request.FILES['file']

with

my_file = self.request.FILES['docfile']

in your views.py

Upvotes: 1

Related Questions