Meed help with following Error:
DoesNotExist at /sales_data/sales_data_import
Product matching query does not exist.
I have two models below, SalesData gets product name from Product. And I am trying to import csv with sales data to SalesData module through function, but it does not work. And I am sure that all the products names in imported csv are included in model Product, so do not understand whey there is DoesNotExists Error.
Models.py:
class Product(models.Model):
name = models.CharField("Product", max_length=150)
def __str__(self):
return f"{self.name}"
class SalesData(models.Model):
date = models.DateField("Date", null=True, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True)
quantity = models.IntegerField("Quantity", null=True, blank=True)
@classmethod
def create_from_csv_line(cls, line):
sd = SalesData()
entry1 = line["Date"]
entry2 = datetime.strptime(entry1,'%d.%m.%Y %H:%M')
date = entry2.strftime('%Y-%m-%d')
sd.date = date
status = str(line["State"])
sd.status = status
curr = str(line["Currency"])
sd.product = Product.objects.get(name=str(line["Items"]))
sd.quantity = int(line["Item quantity"])
sales = float(line["Subtotal"])
if curr == "CZK":
sd.sales = sales * 100/(100 VAT)
else:
sd.sales = c.convert(curr, "CZK", sales, entry2) * 100/(100 VAT)
if status == "fulfilled":
sd.save()
Views.py:
class SalesDataImportView(LoginRequiredMixin, SuccessMessageMixin, FormView):
template_name = "sales_data/sales_data_import.html"
form_class = SalesDataForm
def test_func(self):
return self.request.user.is_superuser
def post(self, request, *args, **kwargs):
form: SalesDataForm = SalesDataForm(request.POST, request.FILES)
if form.is_valid():
csv_file = form.cleaned_data["uploaded_file"]
decoded_file = csv_file.read().decode('utf-8-sig')
io_string = io.StringIO(decoded_file)
reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True)
for line in reader:
SalesData.create_from_csv_line(line=line)
context = self.get_context_data()
my_text = 'New data uploaded successfully.'
messages.success(request, my_text)
return render(request, self.template_name, context)
else:
return self.form_invalid(form)
CodePudding user response:
You have an error here:
sd.product = Product.objects.get(name=str(line["Items"]))
Error: Product matching query does not exist
.
Try to debug. For example:
print(str(line["Items"]))
# before Product.objects.get
Probably the str(line["Items"])
give you an name, which not exists in table Product
.