2016-08-14 11 views
0

HTML5を使用してDjangoフォームに2つのファイルをアップロードすることを検討しています(複数ファイルのアップロードをサポートしているため)。私が直面している問題は、アップロードのための1番目の目標です。保存すると2回保存されるため、2つのファイルがあることがわかります(以下のforループのとおり)。辞書を使って名前をループすると思ったが、this keyword can't be an expressionというエラーが出る。たぶんこれは単純なものですが、もっと必要なものがあれば私は提供することができます。ちょうどメモ、私はファイルのアップロードのためのforms.pyを使用しなかったが、代わりに通常のHTML <inputタグ。ありがとう。Djangoフォームから複数のファイルをモデルに保存

#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}) 

答えて

0

これは私のために働いた方法です。私はのInMemoryUploadedFileをそれぞれrequest.FILES内のにループし、それをrequest.FILESに再度割り当てて、それぞれを1つずつ保存します。

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) 
関連する問題