class home(ListView):
template_name='blog/base.html'
This doesn't work and gives this error --
ImproperlyConfigured at / home is missing a QuerySet. Define home.model, home.queryset, or override home.get_queryset().
but when I create a model with no data
class home(ListView):
model = Post
template_name='blog/base.html'
This works perfectly fine
-> In same way when I don't inherit ListView
class home():
model = Post
template_name='blog/base.html'
It gives the following error in urls.py
from django.urls import path,include
from . import views
from .views import home
urlpatterns = [
# path('',views.home,name='blog-home'),
path('',home.as_view(),name='blog-home')
]
AttributeError: type object 'home' has no attribute 'as_view'
I don't have any idea about both of these
CodePudding user response:
Yes, passing the modal is important in django generic views because ListView inherits from BaseListView which is again inherits from MultipleObjectMixin. The MultipleObjectMixin makes it mandatory to pass modal in the query_set.
See Django code of MultipleObjectMixin to get a better understanding.
CodePudding user response:
I agree to the answer by "Vivek Singh".
But apart from that, your second question where you do not inherit ListView you get the error in urls is because, for as_view() to work, you have to inherit some sort of View class. Such as ListView, DetailView (which come under Generic Views) or just simply View.
CodePudding user response:
In my understanding your questions is rather aiming at "the reason why" and not so much for code:
Django class based ListView/DetailedView etc. are made with the purpose to simplify the typical web pages with a list and details of e.g. products which are stored in a database table (=django model). Thus reducing coding effort. Therefore a model is required that contains the items to list and to detail. If the model given is empty can only be found at runtime when the list page is called an the query is executed - you then just get a web page with an empty product list.
Also inheriting from ListView and defining the model only makes sense if on the rendered html template you use the (automatically) filled context to display the model list.
roughly what happens when you call YourListView.as_view():
-> request
-> dispatch request via urls.py
-> YourListView.as_view()
-> instantiate YourListView with model
-> fill context with query result of the model (!!!)
-> render html template with context
-> return response
(and this is only a small basic example of what ListView can simplify for you)
If you dont need a list/details of a model, there is obviously no need to inherit from those standard views. Then you have simply different needs.
You are free to define your own ClassBased Views, without that functionality provided by ListView etc.
Hope that helps you.
