django-文件上传到很多很多领域

时间:2018-04-11 13:15:49

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

我在模特中有很多领域 -

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

EDITED: views.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');
        }
    });

1 个答案:

答案 0 :(得分: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(...)