gpt4 book ai didi

python - django-多对多字段上的文件上传

转载 作者:行者123 更新时间:2023-12-01 09:33:10 25 4
gpt4 key购买 nike

我的模型中有很多对多的字段-

class A(models.Model):
file = models.ManyToManyField(B, blank=True)

引用模型中的另一个类

class B(models.Model):
filename = models.FileField(upload_to='files/')
user = models.ForeignKey(User)

表单.py

class AForm(forms.ModelForm):
file = forms.FileField(label='Select a file to upload', widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)
class Meta:
model = A
fields = '__all__'

如何让文件上传在这里工作?我在这里建议了基本的views.py - 不起作用 https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html

编辑: View .py

if request.method == 'POST':
a = A()
form = AForm(request.POST, request.FILES, instance=a)
if form.is_valid():
a=form.save()
files = request.FILES.getlist('file')
for f in files:
a.file.create(filename=f, user=request.user)
a.file.add(a.id)
if request.is_ajax():
return JsonResponse({'success': True})
return redirect('file_view', a_id=a.id)
elif request.is_ajax():
form_html = render_crispy_form(form, context=csrf(request).copy())
return JsonResponse({'success': False, 'form_html': form_html})

ajax-

$.ajax({
url: "",
type: "POST",
data: formdata,
contentType: false,
processData: false,
success: function(data) {
if (!(data['success'])) {
// Replace form data
$('#{% if not form_id %}form-modal{% else %}{{ form_id }}{% endif %}-body').html(data['form_html']);
$('#form-submit').prop('disabled', false);
$('#form-cancel').prop('disabled', false);
$(window).trigger('init-autocomplete');
} else {
alertbox('Form saved', '', 'success');
$('#form-submit').prop('disabled', false);
$('#form-cancel').prop('disabled', false);
setTimeout(function () {
location.reload();
}, 2000);
}
},
error: function (request, status, error) {
alertbox('AJAX Error:', error, 'danger');
}
});

最佳答案

我在想这样的事情:

def your_view(request, a_id):
a = A.objects.get(id=int(a_id))

if request.method == "POST" :
aform = AForm(request.POST, instance=a)

if aform.is_valid():
files = request.FILES.getlist('file') #'file' is the name of the form field.

for f in files:
a.file.create(filename=f, user=request.user)
# Here you create a "b" model directly from "a" model

return HttpResponseRedirect(...)

编辑:如果您之前没有创建模型,则无法在 AForm 中使用实例。您正在执行 a=A(),它正在调用 __init__ 方法,但没有创建它。另外,我不得不说,你所做的事情有点奇怪,因为你需要在 A 之前创建 B,以便你可以在 A 文件 ManyToManyField 中看到 B 模型。

def your_view(request):

if request.method == "POST" :
aform = AForm(request.POST, request.FILES)

if aform.is_valid():
a = aform.save() # Here you have the a model already created
files = request.FILES.getlist('file') #'file' is the name of the form field.

for f in files:
a.file.create(filename=f, user=request.user)
# Here you create a "b" model directly from "a" model

return HttpResponseRedirect(...)

关于python - django-多对多字段上的文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49776144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com