Context Processor for Django Site

707 Views Asked by At

I'm builing a wedding website creator (no judgement please).

Almost every view needs to call a Wedding.objects.get(id=wedding_id) and then pass it to the template as part of the variables.

Seems like this is a good use for a custom context processor. Wondering what the best way to create a context processor that would read the URL and if there was a wedding ID, include a wedding object in the template. If there wasn't a wedding ID, then wedding=None in the template.

3

There are 3 best solutions below

2
On BEST ANSWER

First, I would make sure you really need this for almost every request, since you would be coding in an explicit query to each request. A get query is immediate as opposed to a lazy filter. If you wanted to make it more lazy you could wrap the get in a small "get_wedding" wrapper, or use a filter and just grab it from the list...

def add_wedding_context(request):
    id_ = request.GET.get('wedding_id', None)
    wedding = None
    if id_ is not None:
        try:
            wedding = Wedding.objects.get(id=id_)
        except Wedding.DoesNotExist:
            pass
    return {'wedding':wedding}

If you want to try a lazy approach, so that the query only gets run if you actually use the object, you can wrap it in a lazy object:

from django.utils.functional import SimpleLazyObject
from functools import partial

def get_wedd_or_none(id_):
    try:
        return Wedding.objects.get(id=id_)
    except Wedding.DoesNotExist:
        return None

def add_wedding_context(request):
    id_ = request.GET.get('wedding_id', None)
    if id_ is not None:
        lazy = SimpleLazyObject(partial(get_wedd_or_none, id_))
        return {'wedding': lazy}
    else:
        return {'wedding': None}
0
On
import re

def add_wedding_ring(request):
  if re.match('.*/id=.*',request.get_full_path()):
     return {'wid':Wedding.objects.get(id=wedding_id)}
  return {}
0
On

@Brenden why context processor? If you use Django>=1.3 then you can just use class based view like

class ViewWedding(DetailView):
  model = Wedding
  pk_url_kwarg = 'wedding_id'
  template_name = 'you-template.html'
  context_object_name = 'wedding'

Does it worth to have one more context processor instead of passing wedding instance from a view by the way I think its more flexible and preferable way to context_processor?

Thanks,

Sultan