Сохранение CSV в модель в Django
Я пытаюсь разработать представление, которое сохраняет поля CSV в таблицу в модели Django, а затем сохраняет весь CSV в другую таблицу с полем fileField. Однако когда я пытаюсь сохранить весь CSV, я получаю: The 'file' attribute has no file associated with it. Почему так? Как я должен сохранить CSV в поле fileField?
models.py:
class wordsFile(models.Model):
table = models.ForeignKey(WordsTable, on_delete=models.CASCADE)
file = models.FileField(upload_to='uploads/%Y/%m/%d/')
def save(self, *args, **kwargs):
self.file.save(self.file.name, self.file)
views.py:
def home(request):
tp = request.POST.get('tp')
elif tp == "Upload CSV":
if request.user.is_authenticated:
upCSV = request.FILES.get('upload')
decoded_file = upCSV.read().decode('utf-8')
file = wordsFile().save(decoded_file, save=True) #Here is where I try to save the whole CSV to the fileField of the wordsFile model.
io_string = io.StringIO(decoded_file)
usr = User.objects.get(username=request.user)
for idx,row in enumerate(csv.reader(io_string, delimiter=',')):
if idx!=0:
wt = WordsTable()
wt.user = usr
wt.word1 = row[0]
wt.word2 = row[1]
wt.word3 = row[2]
wt.word4 = row[3]
wt.word5 = row[4]
wt.save()
return redirect("home")