[英]Post Dynamic form data using Vue and Django
我正在使用 Vue.js 將數據從 regular.html 表單發布到 Django。幾天來一直在使用 python 和 Django。
我的表單有一部分包含一個區域,允許用戶動態添加表單字段(常規輸入和文件上傳)。 每次用戶添加另一行時,我都會使用索引來增加名稱值。 我不確定 go 如何存儲這些表單數據。
HTML
....
<table class="table" id="documentsTable">
<thead>
<tr>
<th>Type</th>
<th>Number</th>
<th>File</th>
<th>Expiry Date</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(required_document, doc_index) in required_documents" :key="doc_index">
<td>
<select :name="`type${doc_index}`" class="form-control" :ref="`type${doc_index}`">
<option :value="index" v-for="(document_type, index) in document_types">[[document_type]]</option>
</select>
</td>
<td>
<input type="text" :name="`number${doc_index}`" class="form-control" :ref="`number${doc_index}`">
</td>
<td>
<input type="file" :name="`file${doc_index}`" class="form-control" :ref="`file${doc_index}`">
</td>
<td>
<input type="date" :name="`date_expiry${doc_index}`" class="form-control" :ref="`date_expiry${doc_index}`">
</td>
<td>
<button class="btn btn-danger delete-row" @click.prevent="removeRow(doc_index)"><i class="pe-7s-trash"></i></button>
</td>
</tr>
</tbody>
</table>
....Vue Section
...
save() {
form = document.getElementById('individualForm');
var formData = new FormData(form);
axios.post('/customers/individual/store', formData).then((response) => {
}).catch((errors) => {
console.log(errors)
});
}
視圖.py
def store_individual(request):
if request.method == 'POST':
individual_form = IndividualForm(request.POST)
// for dynamic section
required_document_form = RequiredDocumentForm(request.POST, request.FILES)
forms.py
class RequiredDocumentForm(forms.ModelForm):
class Meta:
model = RequiredDocument
fields = ['type', 'number', 'file', 'date_expiry']
TYPES = (('', 'Select Type'), ('passport', 'Passport'), ('national_id', 'National ID'),
('drivers_licence', "Driver's Licence"),
('nis', "NIS Number"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
total_documents = int(args[0]['total_documents'])
for i in range(total_documents):
# type0, #type1, number0, number1, etc
type_field_name = 'type%s' % (i,)
number_field_name = 'number%s' % (i,)
file_field_name = 'file%s' % (i,)
date_expiry_field_name = 'date_expiry%s' % (i,)
self.fields[type_field_name] = forms.CharField(required=False, widget=forms.Select(choices=self.TYPES, attrs={'class': 'form-control', }))
self.fields[number_field_name] = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control', }))
self.fields[file_field_name] = forms.FileField(max_length=32,
widget=forms.ClearableFileInput(attrs={'multiple': False, 'class': 'form-control', }))
self.fields[date_expiry_field_name] = forms.DateField(required=False, widget=SelectDateWidget(attrs={'class': 'form-control', }))
Output
這就是我被困的地方。 在此之后我不知道如何存儲信息。
驗證后調用表單保存 function。
if required_document_form.is_valid():
required_document_form.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.