Reputation: 368
So if I used function views like so :
def messageView(request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records':webpages_list}
return render(request,'index.html',context=date_dict)
And my url resolver looks like this : path('', views.messageView , name='index'),
Every thing is fine, my records are displayed as expected :
HOWEVER, when I try to use class based view like so :
class IndexView(CreateView):
form_class = RegisterUserForm
template_name = "index.html"
def index(self,request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records':webpages_list}
return render(request, self.template_name,context=date_dict )
And url is like so : path('', views.IndexView.as_view(), name='index'),
I get nothing in this case, I've tried looking for simple cases of just returning a context from a class view in django online, but to no avail.
What exactly am I misunderstanding here please ?
Upvotes: 2
Views: 7958
Reputation: 31645
If you are just learning CBVs, start with a simple View
instead of CreateView
. This is the easiest way to migrate from FBVs to CBVs:
from django.views import View
class IndexView(View):
def get(self, request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records': webpages_list}
return render(request, 'index.html', context=date_dict)
def post(self, request):
raise NotImplementedError
Upvotes: 3
Reputation: 1254
You can override get_context_data method.
Put this in your class based view:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['access_records'] = AccessRecord.objects.order_by('date')
return context
It returns a dictionary representing the template context.
Upvotes: 6