9Algorithm
9Algorithm

Reputation: 1257

Context processors and model objects. Django

The question is simple.

In each of my views I need to have the following code:

def my_view(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    # Some code...
    return render(request, 'polls/detail.html', {
            'poll': p
            # The rest of the dict...
        })

So I think It's an appropriate situation to use context processors.

But I don't understand how to give the poll_id argument to my context processor func.

Every suggestion will be very appreciated.

Upvotes: 0

Views: 546

Answers (3)

suhailvs
suhailvs

Reputation: 21720

You have better to use TEMPLATE_CONTEXT_PROCESSORS

a sample TEMPLATE_CONTEXT_PROCESSORS

add a file say custom_processors.py to any of your app with these codes:

def my_view(request):
    p = Poll.objects.filter(pk=1)
    # Some code...
    return {'poll':p[0] if p else '',}

add it to settings.py TEMPLATE_CONTEXT_PROCESSORS like:

TEMPLATE_CONTEXT_PROCESSORS=(
    ...
    '<appname>.custom_processors.my_view',
)

if there isn't any TEMPLATE_CONTEXT_PROCESSORS variable in settings.py then import and append it:

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += ('<appname>.custom_processors.my_view',)

Now you can use {{poll}} in any of your template.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599866

This isn't really an appropriate use of context processors. You might find that generic views are a better fit.

Upvotes: 2

astrognocci
astrognocci

Reputation: 1085

Since context processors are run "globally" (you don't call them directly, but they're run automatically after your view has been processed), i don't think there's an easy way to do what you want.

Why not use a helper function in your views ? Something along the lines of

def get_poll(context, poll_pk):
    context['poll'] = Poll.objects.get(pk=poll_pk)

and then in your view:

def my_view(request):
    conext = {}
    # Some code...
    get_poll(context, your_poll_id)
    return render(...)

Or, depending on your url patterns, you could probably parse the request.path attribute in your context processor to figure out the id you want, but this seems hackish and will break if you change you url design.

Upvotes: 1

Related Questions