1

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

3
  • 2
    add enctype="multipart/form-data" to your form, so the file you are uploading will be saved. Commented Jul 8, 2016 at 18:28
  • Have you setup MEDIA_URL and MEDIA_ROOT? docs.djangoproject.com/en/1.9/topics/http/file-uploads Commented Jul 8, 2016 at 18:37
  • > add enctype="multipart/form-data" to your form oh, miracle! Thank you very mush. I've thought that this is only for uploading several files. It works now, thanks! Commented Jul 10, 2016 at 11:20

1 Answer 1

1

Replace

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

with

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

in your views.py

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But I have the same yet. Changed it in question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.