1

I am trying to upload a file in django.

It allows me to add the file in the form and submits with no errors but nothing gets stored. I am using django-crispy-forms

models.py

class Upload(models.Model):
    upload = models.FileField(upload_to='.')

views.py

class UploadsView(UpdateView):
    form_class = UploadForm
    template_name = 'upload.html'
    model = Upload

forms.py

class UploadForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UploadForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Upload
        fields = ('upload',)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media')

MEDIA_URL = '/media/'

form.html

<form method="POST" action="">{% csrf_token %}
        {{ form|crispy }}
             <input class="btn btn-primary" type="submit" value="Submit" />
             <a href="/home"><button type="button" class="btn btn-danger">Cancel</button></a>
</form>
6
  • try to specify the exact Media root like /home/User/project/static/media Commented Oct 23, 2015 at 11:57
  • Can you post your template html where the form is being rendered? Commented Oct 23, 2015 at 12:14
  • I have just used the {{ form|crispy }} tag in my form Commented Oct 23, 2015 at 12:16
  • changing the media root didn't work Commented Oct 23, 2015 at 12:17
  • Yes, but it's the outer <form> tag I'm interested in. Commented Oct 23, 2015 at 12:19

1 Answer 1

2

You need to change your form tag:

<form method="POST" action="" enctype="multipart/form-data">

From the documentation:

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

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

2 Comments

perfect thank you. Don't know how i missed that from the docs
The only reason I could help was that I literally just fixed the same issue on a project I am working on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.