简体   繁体   中英

Django & Javascript: Passing additional variable for file upload

Alright, guys. I'm stumped. I'm following this blog on uploading a file. I trying to modify it so that I can have my file model have a foreign key on another model. The pop up module works, but submitting it does not. I keep getting a 'anothermodel_id field is required' error when the file is submitted and so I need to pass in the field to my form, but I'm not sure how.

I see the javascript line function (e, data) and I imagine that I need to add the variable here, but I can't seem to do it. I don't know where data is defined.

Model

class File(models.Model):
    anothermodel_id        = models.ForeignKey(anothermodel)
    file              = models.FileField(upload_to=upload_product_file_loc)

Form

class FileForm(forms.ModelForm):
    class Meta:
        model = File
        exclude = ()

views.py

class FileUploadView(View):
def get(self, request):
    files = File.objects.all()
    return render(self.request, 'anothermodel/files.html', {'files': files, 'anothermodel_id': 'rb6o9mpsco'})

def post(self, request):
    form =FileForm(self.request.POST, self.request.FILES)
    print(form.errors)
    if form.is_valid():
        photo = form.save()
        data = {'is_valid': True, 'url': photo.file.url}
    else:
        print('we are not valid')
        data = {'is_valid': False}
    return JsonResponse(data)

html

<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-primary js-upload-photos">
  <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
<input id="fileupload" type="file" name="file" multiple
       style="display: none;"
       data-url="{% url 'anothermodel:file-upload' %}"
       data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

javascript:

$(function () {
$(".js-upload-photos").click(function () {
    $("#fileupload").click(); 
    console.log('we clicked it')
    var anothermodelId = $("#start").find('.anotmodel_idId').val();
    console.log(anothermodelId)
  });
$("#fileupload").fileupload({
    dataType: 'json',
    done: function (e, data) {
      if (data.result.is_valid) {
        $("#gallery tbody").prepend(
          "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
        )
      }
    }
  });

});

anothermodel_id is a ForeignKey to another model and in your case, the field is also must required. When the data is uploaded from the client-side, there is no value sent for the anothermodel_id field. Hence, this field stays unpopulated and you get an error when the form gets saved. There could be a couple solutions for your problem depending on what are you storing in anothermodel_id field.

If the field isn't much important, you can let it stay empty:

class File(models.Model):
    anothermodel_id = models.ForeignKey(anothermodel, blank=True, null=True)
    file = models.FileField(upload_to=upload_product_file_loc)    

In case you are saving something from another model. From what I've understood from your code, you can use the save method from models.Model class:

from django.contrib.auth.models import User

class File(models.Model):
    anothermodel_id = models.ForeignKey(User)
    file = models.FileField(upload_to=upload_product_file_loc)

    def save():
        if self.file:
            anothermodel_id = request.user

    super(File, self).save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM