首页 > 解决方案 > Django & Javascript:为文件上传传递附加变量

问题描述

好吧,伙计们。我难住了。我正在关注这个关于上传文件的博客。我试图修改它,以便我的文件模型在另一个模型上有一个外键。弹出模块有效,但提交时无效。提交文件时,我不断收到“anothermodel_id field is required”错误,因此我需要将该字段传递给我的表单,但我不确定如何。

我看到了 javascript 行function (e, data),我想我需要在这里添加变量,但我似乎做不到。我不知道数据在哪里定义。

模型

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

形式

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

视图.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>"
        )
      }
    }
  });

});

标签: javascriptjquerydjangofile-upload

解决方案


anothermodel_id是另一个模型的 ForeignKey,在您的情况下,该字段也必须是必需的。从客户端上传数据时,不会为该anothermodel_id字段发送任何值。因此,该字段将保持未填充状态,并且在保存表单时会出现错误。根据您在anothermodel_id现场存储的内容,可能有几种解决方案可以解决您的问题。

如果该字段不是很重要,您可以将其留空:

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

如果您从另一个模型中保存一些东西。根据我从您的代码中了解到的,您可以使用类中的save方法models.Model

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)

推荐阅读