File upload gives invalid request in Django using modelform

I am trying to upload a file using the model form, but form.save () gives me a bad request. This is my model:

class cv(models.Model):
    name = models.CharField('Name', max_length=64, null=True)
    path_to_cv = models.FileField('CV', upload_to='/', null=True)

Here is the form:

class Step2(forms.ModelForm):
    class Meta:
    model = cv

Here is a view:

def phdStep2(request):
    if request.method == 'POST':
        form = PhdStep2(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/step/3/')
    else:
        form = PhdStep2()
    return render(request, 'step2.html', {'form': form})

Here is the form template:

<form action="/step/2" method="post" class="well form" role="form" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
    <button type="submit" class="btn btn-primary">
        Submit
    </button>
{% endbuttons %}
</form>

Here is media_root in settings.py:

MEDIA_ROOT = '/home/supertux/PyCharm/myproject/admissions/media'
MEDIA_URL = '/media/'

I read like 10s of such streams and found that the problem of most times was enctype in the form that I already included. Now, as I understand it, this should download the file from its model form, but I always get 400 Bad Request. I want to save the name and file path in the database. What am I doing wrong?

+4
source share
3 answers

upload_to='/' upload_to='%Y/%m/%d' , , django, MEDIA_ROOT. , , , , .

: upload_to -, 100, 1000 , . . , , upload_to='', ? Django 1.6 .

Update2: , . . .

+3

, , .

:

django FileField . * relative, /*

SuspiciousFileOperation, django.core.files.storage, ,

def path(self, name):
try:
    path = safe_join(self.location, name)
except ValueError:
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)
return os.path.normpath(path)
+1

If it upload_to=""doesn’t work, try upload_to=".". Track "." default path is MEDIA_ROOT (in Django 1.6.x)

-2
source

All Articles