1

When I upload the file I get a "POST /submit/ HTTP/1.1" 200 604. When I check to see if the file uploaded I can't find it.

Setting File includes:

 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 MEDIA_URL = '/media/'
 MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Models:

 from django.db import models 

 class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

Forms:

from django import forms
from mysite.uploads.models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['description', 'document']

Views:

 from django.shortcuts import render
 from django.http import HttpResponseRedirect
 from django.core.urlresolvers import reverse

 from mysite.uploads.models import Document
 from mysite.uploads.forms import DocumentForm

def model_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('uploadindex'))
   else:
       form = DocumentForm()
   return render(request, 'uploads/index.html', {
    'form': form
})

Urls:

from django.conf.urls import url

from mysite.uploads  import views

urlpatterns = [
    url(r'^$', views.model_upload, name='uploadindex'),
]

Templates: I am using the multipart/form-data, not sure about why the file wont upload.

 <html>
    <body>
    <form action="{% url "uploadindex" %}" 
       method="post"encytpe="multipart/form-data">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Upload</button>
    </form>
    </body>
 </html>
Jahmul14
  • 329
  • 4
  • 18
  • is the validation for `if form.is_valid():` working? put a print statement in it like `print test` and check in the console if its true. – hansTheFranz Jul 10 '17 at 22:05

2 Answers2

4

My guess is your DocumentForm is not valid, and you're getting an error on the document field but not rendering any feedback in the template to indicate this.

Check that you've set the appropriate encoding on your form tag. That's the most common issue with handling file uploads via Django forms:

Note that request.FILES will only contain data if the request method was POST and the that posted the request has the attribute enctype="multipart/form-data"

https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#basic-file-uploads

Casey Kinsey
  • 1,451
  • 9
  • 16
0
...
if form.is_valid():
        form.save(commit=True)
        return HttpResponseRedirect(reverse('uploadindex'))
else:
    print form.errors
...

It will show you errors in case your document field have any error.

Arun V Jose
  • 3,321
  • 2
  • 24
  • 24