Search code examples
pythondjangodjango-context

Context Processor for Django Site


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.


Solution

  • 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}