I
I
iegor2015-10-02 17:53:03
Django
iegor, 2015-10-02 17:53:03

At what point is the decorated function executed?

Tell me at what point the decorated function is executed. There is a code:

def base(func):
    def wrapped(*args, **kwargs):
        context_dict
        context_dict = {'categories_menu': Category.objects.filter(menu=True)}
        return func(*args, **kwargs)
    return wrapped

@base
def index(request): 
    page_list_new = Page.objects.order_by('-datetime')[:5]
    context_dict['pages_new'] = page_list_new
    return render(request, 'home/index.html', context_dict)

I assumed that the dictionary would be created immediately before the function call, but apparently this is not the case. How can the code be made to work (other than a global variable)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rostislav Grigoriev, 2015-10-02
@iegor

The dictionary is created before the function call, but it is not passed anywhere and nothing is known about it inside the function. In this code, there will be an error for the index function , since the dictionary is not initialized. Try like this:

def base_context(func):
    def wrapped(*args, **kwargs):
        context_dict = {'categories_menu': Category.objects.filter(menu=True)}
        kwargs['context_dict'] = context_dict
        return func(*args, **kwargs)
    return wrapped

@base_context
def index(request, **kwargs): 
    page_list_new = Page.objects.order_by('-datetime')[:5]
    context_dict = kwargs.get('context_dict', {})
    context_dict['pages_new'] = page_list_new
    return render(request, 'home/index.html', context_dict)

E
EvgeniyKonstantinov, 2015-10-02
@EvgeniyKonstantinov

I haven’t picked up Python for a long time, but I’ll try
First base is executed
Then index
The problem is not in order, but that context_dict is only in the scope of the base function.
Accordingly, you can pass the context_dict dictionary to index by adding it to the function arguments when it is called in decorator:
As a result, your year should look something like this:

def base(func):
    def wrapped(*args, **kwargs):
        context_dict = {'categories_menu': Category.objects.filter(menu=True)}
        kwargs['context_dict'] = context_dict
        return func(*args, **kwargs)
    return wrapped

@base
def index(*args, **kwargs): 
    page_list_new = Page.objects.order_by('-datetime')[:5]
    context_dict = kwargs['context_dict']
    context_dict['pages_new'] = page_list_new
    return render(request, 'home/index.html', context_dict)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question