Search code examples
pythondjangoattributeerror

AttributeError: module in Django, Python


Getting the following error

File "C:\Users\abc\Projects\ecom\src\ecom\urls.py", line 33, in <module>
path('products/', views.ProductListView.as_view()),
AttributeError: module 'ecom.views' has no attribute 'ProductListView'

ecom/src/ecom/url.py

from products.views import ProductListView, product_list_view

from . import views

urlpatterns = [
path('', views.home_page),
path('login/', views.login_page),
path('register/', views.register_page), 
path('products/', views.ProductListView.as_view()),
path('products-fbv/', views.product_list_view),
path('admin/', admin.site.urls),
]

ecom/src/products/views.py

from django.views.generic import ListView
from django.shortcuts import render


from .models import Product


class ProductListView(ListView):
    queryset = Product.objects.all()
    template_name="products/list.html"



def product_list_view(request):
    queryset=Product.objects.all()
    context={
    'qs':queryset
    }
    return render(request,"products/list.html", context)

Tried changing urlpatterns and products nothing worked.


Solution

  • Well you specify that the views.py file is ecom/src/products/views.py. So that means that the module is products.views. You actually already import that. But in your urls.py, you write views.ProductListView, whereas that views module is actually the one of ecom. You thus should not reference it through views.ProductListView, but for example import it like you did, and then reference it directly.

    If you thus want to reference this view, you can use:

    from products.views import ProductListView, product_list_view
    
    from . import views
    
    urlpatterns = [
        path('', views.home_page),
        path('login/', views.login_page),
        path('register/', views.register_page), 
        path('products/', ProductListView.as_view()),
        path('products-fbv/', product_list_view),
        path('admin/', admin.site.urls),
    ]