0

I am using Vue js to post data from a regular .html form to Django. Been using python and Django for a few days now.

There is a section of my form which contains an area that allows the user to dynamically add form fields(regular inputs and file uploads). I increment name value by using the index everytime the user adds another row. I am not sure how to go about storing these form data.

enter image description here


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

views.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', }))

The Output

  • The output of the "print(request.POST)" is outputted in a QueryDict
  • The output of the "print(request.FILES)" is outputted in a MultiValueDict

enter image description here

This is where I'm stuck. I don't how to store the information after this.

user2538755
  • 314
  • 1
  • 6
  • 21

1 Answers1

0

Call the form save function after validation.

if required_document_form.is_valid():
    required_document_form.save()
martinii
  • 141
  • 10
  • This doesn't work because it's not recognizing that files(stored within the request.FILES) where added so validation error is being thrown. – user2538755 Feb 14 '20 at 02:34
  • https://stackoverflow.com/questions/55845313/serialize-multiple-inmemoryuploadedfile-using-listfield-django-rest-framework. Maybe use this after form is_valid – martinii Feb 15 '20 at 01:55