javascript - 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>"
)
}
}
});
});
解决方案
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)
推荐阅读
- .net - 转换一个 ValueTask
到非通用 ValueTask - javascript - 如何返回函数执行所花费的稳定时间
- bash - 如何将 bash 命令的输出传递给 Github Action 参数
- java - 安卓俄罗斯方块(鬼片/影片)
- r - 条形图制动轴值上的对数刻度
- python - 将张量列表转换为张量的张量
- javascript - 将值从 Jsp 传递到 Javascript 的问题
- flutter - 如何在构建方法中处理文本小部件的空数组?
- python - 导入时错误无法从“werkzeug”导入名称“cached_property”[`from werkzeug.utils import cached_property`]
- javascript - 对象作为 React 子对象无效(找到:带有键 {weight} 的对象)。如果您打算渲染一组孩子,请改用数组