2๐
โ
1.Create one model form
class UserDataForm(forms.ModelForm):
// code here
class Meta:
model = UserData
2. make the excel sheet data to dictionary format using.
from pandas import *
xls = ExcelFile('path_to_file.xls')
df = xls.parse(xls.sheet_names[0])
ref: Python Creating Dictionary from excel data.
3.Instantiate the model form with the dictionary data and check for validation. if the data is valid check for the db entry for the same or use django model_name.get_or_create()
form = UploadFileForm(request.POST,
request.FILES)
if form.is_valid():
# code here to convert to dictionary
data = data_in_dict_form
user_data_form = UserDataForm(data=data)
if user_data_form.is_valid():
obj, created = UserData.objects.get_or_create(**user_data_form.cleaned_data)
# this will create new entry if doesnt exist and just get from db if already exist.
# You can ause any method to create an entry to the data base. you can also just .filter().exists() to check if there is an existing entry. if It returns True you dont need to save it.
# Your Response
else:
# your Response
Note: If there are multiple rows , each rows are for separate entries in db. you need to loop each rows and validate and save()/Do_not_save. ๐
I hope this would help you to get the problem resolved.
๐คVipul Vishnu av
Source:stackexchange.com