'Import csv file using django - Exception Type: DatabaseError
I am trying to create a django project and I need to upload a csv file and create objects.
I found a video: https://www.youtube.com/watch?v=t3BdM6JlAmY and https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html.
My code: sales/model.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Sales(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.CharField(max_length=10, blank=False, null= False)
product = models.CharField(max_length=10, blank=False, null= False)
def __str__(self):
return f"{self.user}"
sales/admin.py
from django.contrib import admin
from .models import Sales
admin.site.register(Sales)
In the main project, settings, I added that part about Media.
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('csvs.urls', namespace='csvs')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
csvs/models.py
from django.db import models
class Csv(models.Model):
file_name = models.FileField(upload_to='csvs')
uploaded = models.DateTimeField(auto_now_add = True)
activated = models.BooleanField(default= False)
def __str__(self):
return f"File id: {self.id}"
csvs/forms.py
from django import forms
from .models import Csv
class CsvModelForm(forms.ModelForm):
class Meta:
model = Csv
fields =('file_name',)
and views.py
from django.shortcuts import render
from .forms import CsvModelForm
from .models import Csv
import csv
from django.contrib.auth.models import User
from sales.models import Sales
def upload_file_view(request):
form = CsvModelForm(request.POST, request.FILES)
if form.is_valid():
form.save()
form = CsvModelForm()
obj= Csv.objects.get(activated=False)
with open(obj.file_name.path, 'r') as f:
reader = csv.reader(f)
for i, row in enumerate(reader):
if i==0:
pass
else:
#row = "".join(row)
#row = row.replace(";"," ")
#row=row.split()
#print(row)
#print(type(row))
date = row[1]
user = User.objects.get(username=row[0])
Sales.objects.create(
date=date,
product= row[2],
user=user,
)
obj.activated=True
obj.save()
return render(request, 'upload.html', {
'form': form
})
The error that I have after I upload the file is "Exception Type: DatabaseError". If I scroll more down, I see that I have an exception on this line.
I want to mention that I am working with the mongodb. If I try all the code for sqlite3 data base, all is good and I don't have any problem.
And I tried to delete all the migrations and do the steps with makemigrations, migrate, create superuser, but nothing happened.
Thanks for your time!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
