Django - Multiple File upload data not inserted in model database

210 views Asked by At

I have implemented a feature to upload multiple files for each RetailerMaster(as foreign key). Once I migrate this model to microsoft sql server, FileUpload model is created without primary key which django should be creating automatically. Also if i upload multiple file, then only one record is created in database and it keeps on updating for each file.

models.py

class RetailerMaster(models.Model):
    id = models.PositiveIntegerField(unique=True)
    name = models.CharField(max_length=1000)
    address = models.CharField(max_length=4000)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    pincode = models.CharField(max_length=100)
    contact_name = models.CharField(max_length=500)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    erp = models.CharField(max_length=1000)
    remark = models.CharField(max_length=4000)

    def __str__(self):
        return self.id

class FileUpload(models.Model):
    retailer = models.ForeignKey(RetailerMaster, on_delete=models.CASCADE),
    file = models.FileField(upload_to='files')
    file_upload_datetime = models.DateTimeField()
    file_name = models.CharField(max_length=1000)

views.py

retailer = RetailerMaster.objects.get(retailer_id=retailer_id)
register_complete = retailer

files = request.FILES.getlist('file')
file_upload_datetime = file_upload_form.cleaned_data['file_upload_datetime']
for f in files:
    print(f.name)
    file_instance = FileUpload(register_complete.id,f,file_upload_datetime,f.name)    
    file_instance.save()

migrations file

migrations.CreateModel(
    name='FileUpload',
    fields=[
        ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
        ('file', models.FileField(upload_to='files')),
        ('file_upload_datetime', models.DateTimeField()),
        ('file_name', models.CharField(max_length=1000)),
    ],
)

Why migration file is not having foreign key?

template file

<div id="registrationForm">
  <form
    action="{% url 'retail_forms:file-upload' %}"
    method="post"
    enctype="multipart/form-data"
  >
    {% csrf_token %} {{ retailer_registration_form|crispy }} {{ file_upload_form|crispy }}
    <input type="submit" value="Register" class="btn btn-primary" />
  </form>
</div>

eg: If two files are uploaded 001.xlsx and 002.xlsx then below happens in database. As actual result, one record is inserted rather than two and same is updated with last file uploaded from multiple files.

enter image description here

Can anyone help why record is not inserted but just updated.

1

There are 1 answers

0
Ronak On BEST ANSWER

Problem is fixed by removing trailing comma for foreign key in FileUpload Model.

django - Foreign key not getting created from model