I have a excel file with various columns and rows. I upload this file and saves the data in the database.But i am having a problem and need help in figuring out this issue :-
1) Upload the file with the same name but with different contents uploads the previous file data.
So let say i upload abc.xls having 3 rows it uplods 3 rows but if i upload the another file with 10 rows having the same name abc.xls it shows the result of previously uploaded file and displays only 3 results.
I tried unique files like but then i have No such File or Directory.
# Models.py
class ExcelFile(models.Model):
excel_file = models.FileField(upload_to='documents/')
class Meta:
verbose_name = 'ExcelFile'
verbose_name_plural = 'ExcelFiles'
def __unicode__(self):
return self.excel_file.name
In the admin i see the files are already unique like abc_1.xls, abc_2.xls and so on. Here is my code
#views.py
if request.method == "POST":
form_data = ImportExcelForm(request.POST, request.FILES)
if form_data.is_valid():
cd = form_data.cleaned_data
file_obj, created = ExcelFile.objects.get_or_create(excel_file=cd['excel_file'])
try:
data_list = excel_parser(cd['excel_file'].name.replace(" ", "_"))
except:
data_list = excel_parser(get_correct_filename(cd['excel_file']))
########### and so on #######################
def get_correct_filename(filename):
replacements = {"(": "", ")": ""," ":"_"}
new_file = "".join(replacements.get(c, c) for c in filename.name)
return new_file
def excel_parser(filename):
"""
Excel file will first come here. It will be read sheetwise.
This functions will return a data list.
"""
file_path = settings.MEDIA_ROOT + 'documents/' + filename
#Here it is reading abc.xls only as the filename is abc.xls
book = open_workbook(file_path)
data_list = []
sheet_list = []
total_sheets = book.nsheets
for sheet in range(total_sheets):
sheet_counter = book.sheet_by_index(sheet)
data_list = extract_data(book,sheet)
sheet_list.append(data_list)
return sheet_list