Axel
Axel

Reputation: 1475

File upload using Django and Bootstrap not working

I am using an automatically generated Bootstrap form to allow the user to upload files to the database. The form is generated inside a modal like this:

<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Dateien hinzufügen</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form method="post" enctype="multipart/form-data">
        <div class="modal-body">
          {% csrf_token %}
          {% bootstrap_form form %}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button>
          <button type="submit" class="btn btn-primary">OK</button>
        </div>
      </form>
    </div>
  </div>
</div>

using a Django form and file structure that look like this:

import django.forms as forms
from .models import StandaloneFile

# Create the form class.
class StandaloneFileForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta:
        model = StandaloneFile
        fields = ['file', 'profile', 'description']

and

from django.db import models

# Create your models here.

def file_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/<profile.abbr>/<filename>
    return '{0}/{1}'.format(instance.profile.abbr, filename)

class StandaloneFile(models.Model):
    file = models.FileField(upload_to=file_directory_path)
    profile = models.ForeignKey('MeasurementProfile',on_delete=models.SET_NULL,null=True)
    description = models.TextField()
    date_uploaded = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.file.name.split("/")[-1]

Now if I click the submit button the fields file, profile and description should be send via POST however if I look at request.POST only the fields file and profile are send and the variable file does not exist.

What did I do wrong here?

Upvotes: 0

Views: 569

Answers (1)

Alb
Alb

Reputation: 1125

# This text is here to fill the answer to get to 30 characters minimum
request.FILES

Upvotes: 1

Related Questions