Django - simplelazyobject breaks templated filter

Here's a templated filter that worked without issue until recently, before updating the Django source:

from pm_core.models import PMUser 
@register.filter 
def can_manage_market(user, market): 
    if not isinstance(user, PMUser): return False 
    return user.can_manage_market(market) 

      

The filter started to always return false. The problem seems to be that the user instance is "SimpleLazyObject" instead of PMUser (a subclass of user). A search on the Internet led me to Ticket # 12049, which indicates that it could be a similar error (however, unfortunately, there is no fix, unfortunately).

I would appreciate any information about this simplelazyobject that I was not aware of before.

ps. I also posted this question on the django-users group, but have not received an answer yet.

+2


source to share


3 answers


This issue was filed as a bug (ticket # 12060 ) and officially accepted. Thank Peter and Daniel for their help.



EDIT: The problem is fixed in changeset 11637 .

+1


source


As Peter says, this is due to the changes in block 11626. The reason this now gives you a wrapper rather than an object is because of the "laziness" of that wrapper object. It is designed so that if you don't actually do anything with it, it never gets the underlying User object - this is for cache optimization considerations. Since all you are doing is type checking and not evaluating the object, the LazyObject remains and your test fails.

Instead of checking that the object is of a certain type, which is not Pythonic anyway, you should check that your object has methods or attributes that you want to call. The wrapper should pass them transparently and your test will succeed.



try:
    return user.can_manage_market(market)
except AttributeError:
    return False

      

+2


source


Change 11626 (checked a few days ago) changed the user definition in django.core.context_processors from ContextLazyObject to SimpleLazyObject. My coffee hasn't fully hit yet, but it looks like this might be the source of your problem. You may need to put a wrapper around this or modify your test.

0


source







All Articles