I am trying to save a whole CSV file uploaded from a form through a Django view. However, when I click the button to upload the CSV to the FileField I get 'str' object has no attribute 'file'
I have seen some questions like this but I haven't managed to save the CSV in the model. What am I missing?
The model:
class wordsFile(models.Model):
table = models.ForeignKey(WordsTable, on_delete=models.CASCADE)
file = models.FileField(upload_to='media/%Y/%m/%d/', blank=True, null=True)
def save(self, *args, **kwargs):
self.file.save(self.file.name, self.file, save=False)
views.py:
def home(request):
if request.method == 'POST':
tp = request.POST.get('tp')
if tp == "Upload CSV":
if request.user.is_authenticated:
upCSV = request.FILES.get('upload')
wordsFile.save(upCSV.name, upCSV) #HERE is where I save the CSV to the FileField
decoded_file = upCSV.read().decode('utf-8')
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")
The form:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="upload" accept=".csv, .xlsx" value="Upload">
<br>
<input type="submit" id="btnupload" class="button btn btn-primary" name="tp" value="Upload CSV">
</form>