views:

45

answers:

1

On views that allow updating/deleting objects, I need a decorator that verifies that the object to be edited belongs to a group(model "loja). Both defined in the url:

/[slug model loja--s_loja]/[viewname-ex:addmenu]/[object id--obj_id]

Because the model of the object can vary, the decorator the model of the object as an argument. Every model that may be passed as an argument has a foreign key to the model "loja" named loja.

The decorator:

def acesso_objecto(modelo):
    def wrap(f):
        def wrapper(*args, **kwargs):
            s_loja = kwargs['s_loja']
            obj_id = kwargs['obj_id']
            objecto = get_object_or_404(modelo, pk=obj_id)
            loja = get_object_or_404(Loja, slug=s_loja)
            if objecto.loja is not loja:
                raise Http404
            else:
                return f(*args, **kwargs)
        return wrapper
    return wrap

Basically, unless the group "loja" and the object exists and the object belongs to that group a 404 error should be raised.

Without the decorator the view works fine, but the decorator always raises 404 because the if statement is always true even when it shouldn't be. If I use the loja.id or loja.slug for verification it works as THEY ARE related, but this function always seems to fail and I have no idea why.

+1  A: 

Replace is not with !=.

not loja is evaluating to True, and the if statement is testing the equality between objecto.loja and True.

a paid nerd
Well, that was stupid. I thought is not was the same as !=But I'm not sure about not loja evaluating to True. It would be contrary from the docs.From the python docs:"The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value." Then as a footnote:" Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the is operator, like those involving comparisons between instance methods, or constants."
Ricardo B.
Ah, you're right, and I was wrong about the `is` operator. I should have quoted the docs like you did. :-)
a paid nerd
still, you pointed to the right direction. Thanks
Ricardo B.