I am working on a school management project and want to upload a CSV file and save it either by overriding the current data or updating it in the database. but it's not being added in the database. Also, I like to add more fields so if possible using dynamic(i.e. by loops) so I don't have to change it later.
models.py
class Student(models.Model):
registration_number = models.CharField(max_length=200, unique=True)
firstname = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
date_of_birth = models.DateField(default=timezone.now)
current_class = models.ForeignKey(StudentClass, on_delete=models.SET_NULL, blank=True, null=True)
date_of_admission = models.DateField(default=timezone.now)
parent_mobile_number = models.CharField(max_length=15)
address = models.TextField()
class StudentBulkUpload(models.Model):
date_uploaded = models.DateTimeField(auto_now=True)
csv_file = models.FileField(upload_to='students/bulkupload/')
forms.py
class StudentBulkUploadForm(forms.ModelForm):
class Meta:
model = StudentBulkUpload
fields = ("csv_file",)
views.py
def uploadcsv(request):
if request.method == 'GET':
form = StudentBulkUploadForm()
return render(request, 'students/students_upload.html', {'form':form})
# If not GET method then proceed
try:
form = StudentBulkUploadForm(data=request.POST, files=request.FILES)
if form.is_valid():
csv_file = form.cleaned_data['csv_file']
if not csv_file.name.endswith('.csv'):
messages.error(request, 'File is not CSV type')
return redirect('students:student-upload')
# If file is too large
if csv_file.multiple_chunks():
messages.error(request, 'Uploaded file is too big (%.2f MB)' %(csv_file.size(1000*1000),))
return redirect('students:student-upload')
file_data = csv_file.read().decode('utf-8')
lines = file_data.split('\n')
# loop over the lines and save them in db. If error, store as string and then display
for line in lines:
fields = line.split(',')
data_dict = {}
print(data_dict)
try:
form = StudentBulkUploadForm(data_dict)
if form.is_valid():
form.save()
else:
logging.getLogger('error_logger').error(form.errors.as_json())
except Exception as e:
logging.getLogger('error_logger').error(form.errors.as_json())
pass
except Exception as e:
logging.getLogger('error_logger').error('Unable to upload file. ' + repr(e))
messages.error(request, 'Unable to upload file. ' + repr(e))
return redirect('students:student-upload')
student_upload.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-success" value="Submit">
</form>