将多个文件从Django Forms保存到Model

时间:2016-08-14 01:21:01

标签: 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})

1 个答案:

答案 0 :(得分:1)

这是一种适合我的方式。我在request.FILES中循环每次出现 InMemoryUploadedFile 并将其重新分配给request.FILES,然后逐个保存。

<强> forms.py

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

<强> views.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)