timi95
timi95

Reputation: 368

Return context from class based view in django

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 : enter image description here

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

Answers (2)

Max Malysh
Max Malysh

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

T.Tokic
T.Tokic

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

Related Questions