Reputation: 27
I am trying to access model data in a template using the view class method (that I have done before), however the "NameError: name 'context' is not defined" continues to arise.
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from .models import Email
class MapView(TemplateView):
template_name = 'Map/map.html'
email = Email.objects.all()
context = {'email': email}
def get(self, request):
return render(request, self.template_name, context)
if I replace "context" with an empty dictionary "{}" then I can display the template, but even if i declare "context = {}" and try to return "render(request, self.template_name, context)" I still get the context is not defined error.
Upvotes: 0
Views: 807
Reputation: 16032
Class attributes are not in the scope of class methods (ie they aren't defined). If you need to access a class attribute from within a method, you can do this via self
:
class MapView(TemplateView):
template_name = 'Map/map.html'
email = Email.objects.all()
context = {'email': email}
def get(self, request):
return render(request, self.template_name, self.context)
Upvotes: 0