Django & Javascript:为文件上传传递附加变量



好了,伙计们。我被难住了。我正在关注这个博客上传一个文件。我试图修改它,这样我就可以让我的文件模型在另一个模型上有一个外键。弹出模块工作,但提交它不工作。提交文件时,我不断收到一个"anotheromedel_id字段是必需的"错误,因此我需要将该字段传递给我的表单,但我不确定如何传递。

我看到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 = ()

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是另一个模型的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)    

以防您正在从另一个模型中保存某些内容。根据我从您的代码中了解到的内容,您可以使用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)