Created a function in admin.py to iterate over rows in a csv file. The csv file has “Budget Item” that contains the text value of the ForeignKey (FK) in the model I’m mapping to. I have to change the text values to the numeric id of the FK.
for ind, row in df.iterrows():
created = Ledger.objects.update_or_create(
date = row['Date'],
description = row['Description'],
# Field 'id' expected a number but got 'Administration'
budget_item = row['Budget Item'],
How would one replace the id number with the text value in the csv file for importing to the FK field?
@admin.register(Ledger)
class LedgerAdmin(admin.ModelAdmin):
list_display = ('date',
'budget_item',
'description',
'credit',
'debit',
'reconciled')
# for the CSV upload
def get_urls(self):
urls = super().get_urls()
new_urls = [path('upload_csv/', self.upload_csv),]
return new_urls + urls
# CSV Upload
def upload_csv(self, request):
if request.method == "POST":
csv_file = request.FILES["csv_upload"]
if not csv_file.name.endswith('.csv'):
messages.warning(request, 'Error, CSV File required.')
return HttpResponseRedirect(request.path_info)
# Using Pandas to clean the file.
df = pd.read_csv(csv_file)
print(df)
items = Ledger.objects.all()
print(items)
# csv to DB model mapping without checking the data. You'll need to make sure
# the file has been cleaned.
# @ Add a data checking routine.
for ind, row in df.iterrows():
created = Ledger.objects.update_or_create(
date = row['Date'],
description = row['Description'],
# Field 'id' expected a number but got 'Administration'
budget_item = row['Budget Item'],
#budget_item_id = row['Budget Item'],
#budget_item = Ledger.objects.get(budget_item=row['Budget Item']),
credit = row['Credit'],
debit = row['Debit'],)
url = reverse('admin:index')
return HttpResponseRedirect(url)
# CsvImportForm() added above
form = CsvImportForm()
data = {"form": form}
return render(request, 'admin/csv_upload.html', data)