简体   繁体   English

Django和Javascript:传递用于文件上传的其他变量

[英]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. 提交文件时,我不断收到“ anothermodel_id字段为必填”错误,因此我需要将该字段传递给表单,但是我不确定如何传递。

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. 我看到了javascript行function (e, data)并且我想我需要在此处添加变量,但是我似乎做不到。 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 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 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: 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. anothermodel_id是一个ForeignKey到另一个模型,并在你的情况下,也必须需要的领域。 When the data is uploaded from the client-side, there is no value sent for the anothermodel_id field. 从客户端上传数据时,没有为anothermodel_id字段发送任何值。 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. 根据您存储在anothermodel_id字段中的内容,可能有几种解决方案。

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: 根据我对代码的了解,可以使用models.Model类中的save方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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