1

So, I'm trying to access the variable store in get_queryset() from get_context_data(). I though I can deal with that by using a global variable. But it didn't work too. Is there any other way to do that?

class StoreDetailView(ListView):

    def get_queryset(self):
        print(store) # an error happens
        ...


    def get_context_data(self, **kwargs):
        context = super(StoreDetailView, self).get_context_data(**kwargs)

        context['store'] = Store.objects.filter(domainKey=self.kwargs['store_domainKey'])
    context['store'] = get_object_or_404(Store, domainKey=self.kwargs['store_domainKey'])

        store = context['store']
        ...
5
  • Why don't you access the query inside get_queryset? Commented May 14, 2018 at 18:53
  • @Lemayzeur The query starts from a value in kwargs. So, whatever I do in the middle, it needs to start in get_context_data, and needs to be done in get_queryset() to use pagination. Commented May 14, 2018 at 18:55
  • 1
    You have access to self.kwargs['store_domainKey'] in get_queryset,, no need to do it in context_Data Commented May 14, 2018 at 18:57
  • 2
    actually, your get_queryset should handle the queryset at all, get_context_data is only to send more data to templates via context Commented May 14, 2018 at 18:58
  • Since I'm new to Django, I don't even know what I'm doing right now lol. The more I write, the more confused I am. I need to study more to figure out what each function is actually supposed to do. Thanks anyways! Commented May 14, 2018 at 19:01

1 Answer 1

2

you can use self, to make it a class variable

# set variable
self.store = context['store']

# get variable
print(self.store) 
Sign up to request clarification or add additional context in comments.

6 Comments

am I wrong or this doesn't exist in python? you meant self
It causes an error "name 'this' is not defined". Why is that?
@Lemayzeur self also shows an error 'StoreDetailView' object has no attribute 'store' as well
@Jay yes use self. thanks @Lemayzeur for the update
get_queryset method executing before get_context_data that's why you are getting error means you are trying to get value of variable which is not defined yet
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.