将多个文件从 Django 表单保存到模型

Ker*_*vvv 3 python django django-models django-forms django-views

希望使用 HTML5 将 2 个文件上传到 Django 表单中(因为它支持多文件上传)。我面临的问题是它的目标是第一个上传。它知道有 2 个文件,因为当它保存时,它会保存两次(根据下面的 for 循环)。我想使用字典来循环名称,但我收到一条错误,提示this keyword can't be an expression. 也许这很简单,但如果您需要更多,我可以提供。请注意,我没有使用 forms.py 进行文件上传,而是仅使用常规 HTML<input标签。谢谢。

#page.html
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form_a.as_p }}
    <input type="file" name="img" multiple>
    <input type="submit" value="Submit" />
</form>


#models.py
def contact(request):
    if request.method == 'POST':
        form_a = RequestForm(request.POST, request.FILES)
        if form_a.is_valid():
        #assign form data to variables
            saved_first_name = form_a.cleaned_data['First_Name']
            saved_last_name = form_a.cleaned_data['Last_Name']
            saved_department = form_a.cleaned_data['Department']
            saved_attachments = request.FILES.getlist('img')
        #create a dictionary representing the two Attachment Fields
        tel = {'keyword1': 'Attachment_2', 'keyword1': 'Attachment_1'}

        for a_file in saved_attachments:
        #for every attachment that was uploaded, add each one to an Attachment Field
            instance = Model(
                Attachment_1=a_file,
                Attachment_2=a_file
            )
            instance.save()
        all_together_now = Model(First_Name=saved_first_name, Last_Name=saved_last_name, 
            Department=saved_department, Attachment_1=???, Attachment_2=???)
        #save the entire form
        all_together_now.save()
    else:
    #just return an empty form
        form_a = RequestForm()
    return render(request, 'vendor_db/contact.html', {'form_a': form_a})
Run Code Online (Sandbox Code Playgroud)

Saz*_*zzy 7

这是一种对我有用的方法。我循环 request.FILES 中每次出现的InMemoryUploadedFile并将其重新分配回 request.FILES,然后逐一保存。

表格.py

class PhotosForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta:
        model = Photos
        fields = ['file']
Run Code Online (Sandbox Code Playgroud)

视图.py

def photos(request):
    photos = Photos.objects.all()
    if request.method == 'GET':
        form = PhotosForm(None)
    elif request.method == 'POST':
        for _file in request.FILES.getlist('file'):
            request.FILES['file'] = _file
            form = PhotosForm(request.POST, request.FILES)
            if form.is_valid():
                _new = form.save(commit=False)
                _new.save()
                form.save_m2m()
    context = {'form': form, 'photos': photos}
    return render(request, 'app/photos.html', context)
Run Code Online (Sandbox Code Playgroud)