Home > other >  NameError at/ name 'Product' is not defined
NameError at/ name 'Product' is not defined

Time:02-15

I've been working on this eCommerce website and its been working perfectly but today when I ran the server it's showed me " NameError at/ name '

Product' is not defined

" I've looked Into the code several times and didn't spot any error

Models.py

Class Product(models.Model):
   ""
   ""
   def __str__(self)
      self.name

Views.py

From .models import *
def ShowProducts(request):
   items= Product.objects.all()
   context = {'items':items}
   return render(request, 'home.html', context=context)

urls.py

from . import views

urlspatterns=[
     Path ('', views.ShowProducts, name ='showproducts')
]

My greatest surprise is , when I change the line, item= Product.objects.all() to items= () in views.py,. It displays the website correctly although without any product in it, please what should I do

CodePudding user response:

There could be 2 reasons.

  1. In the code From .models import * the From should be from. F is capital.
  2. Models file path in from .models import * maybe from ..models import * is the correct path.

If you can share the directory structure then it may help.

CodePudding user response:

Problem:

Ideally, I believe the error you might be getting is:

NameError: name 'product' is not defined

Solution

This means that you should have a product attribute or alternatively, you may not have run the necessary migrations for your app.

Please add the attributes/fields that your require in your Product class(note that class begins with lower-case c in python, i.e class Product) & then run the migrations. Your Product class seems to be lacking. Update it accordingly.

class Product(models.Model):
   # insert your fields here eg as below
   name = models.CharField(max_length=255)

   def __str__(self)
      self.name
  • Related