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