【问题标题】:django- file upload on many to many fielddjango-在多对多字段上上传文件
【发布时间】:2018-04-11 13:15:49
【问题描述】:

我在模型中有一个多对多字段-

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

引用模型中的另一个类

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

forms.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

编辑: 视图.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');
        }
    });

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    我在想这样的事情:

    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(...)
    

    【讨论】:

    • 感谢 DavidRguez 的回复,它仍然给我一个错误“未选择文件”,我在您的建议中另外添加了 aform.save() 语句。有什么指点吗?
    • 我需要查看您的模板才能全面了解您在做什么。请查看我的编辑以获取更多信息。
    • 更新了视图和模板——现在,表单——无论输入或不输入似乎都是无效的,因为它会呈现清晰的 _forms 响应。请建议
    • 我也理解你做 a=A() 的观点,但是如何创建新模型呢?
    • 嗨大卫,发生的事情是 formdata 是空的。我检查了 chrome 开发人员工具中的网络选项卡,请求有效负载部分为空,我不确定为什么会这样:(
    猜你喜欢
    • 2022-11-20
    • 2023-03-31
    • 2016-06-09
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多