Reputation: 6128
I would like to get some indicators about get()
and get_context_data()
classes because I get an issue and I'm trying to understand why.
I have a Django DetailView
which let to display some statistics with multiple querysets. In the same class, I have a query string
which shows the result from a get queryset.
My code looks like this :
class StatsView(DetailView):
""" Create statistics pageview """
template_name = 'app/stats.html'
def get(self, request):
return render(request, self.template_name, context)
def set_if_not_none(self, mapping, key, value):
if value is not None:
if len(value) != 0:
mapping[key] = value
def get_context_data(self, **kwargs):
return context_data
Like this, get_context_data()
function doesn't work, but when I set get()
in comment, it works fine. I think there is a small misunderstanding from myself.
Maybe I don't use the good django generic display view or maybe it's not possible to use get()
and get_context_data()
together in the same class ?
Thank you
I read the Django documentation but I would like to get explanations from you
EDIT:
I'm trying to pass querysets from get()
method to get_context_data()
. Then I removed get()
method, I changed DetailView
by TemplateView
and it works with just get_context_data()
. But how I can add a "skeleton" without get()
method ?
Upvotes: 1
Views: 1156
Reputation: 88499
I'm trying to pass querysets from get() method to get_context_data()
class StatsView(DetailView):
""" Create statistics pageview """
template_name = 'app/stats.html'
def get(self, request, *args, **kwargs):
queryset = SampleModel.objects.all()
return render(request, self.template_name, context=self.get_context_data(queryset=queryset))
def set_if_not_none(self, mapping, key, value):
if value is not None:
if len(value) != 0:
mapping[key] = value
def get_context_data(self, **kwargs):
qs = kwargs.get('queryset')
# do something
If your overriding get_context_data()
method, it's advaisable to call the super()
method as
class StatsView(DetailView):
# your code
def get_context_data(self, **kwargs):
data = super(StatsView, self).get_context_data(**kwargs)
data.update({"foo": "bar"})
return data
I would like to get some indicators about
get()
andget_context_data()
I think it's nicely answered here already , When to use get, get_queryset, get_context_data in Django?
Upvotes: 4