django-native-tags icon indicating copy to clipboard operation
django-native-tags copied to clipboard

Context variable is not set if None is returned

Open lukaszb opened this issue 15 years ago • 2 comments

Lets say we have such function:

def fetch_user(username):
    try:
        return User.objects.get(username=username)
    except User.DoesNotExist:
        return None
fetch_user.function = True

Now let say we have users with usernames "admin", "lukaszb" in a database. And we use "fetch user" in a loop for following names: username_list = ["admin", "marcink", "lukaszb"]. Like that:

{% for username in username_list %}
    {% fetch_user username as "author" %}
    {{ author }}
{% endfor %}

Result is: "admin admin admin"

If we use username_list = ["marcink", "admin", "marcink", "lukaszb"] we got: "None None None None".

lukaszb avatar May 14 '10 08:05 lukaszb

Here is what the real problem is. The first time through that loop the 'author' variable is undefined until you set it w/ the first fetch_user call. The second time through the loop it sees that author is set in context and instead of using the string 'author' it uses the username of the user found in the first call (since user objects can be cast as strings) At the core of this problem is native_tags parsing which uses the shlex.split method which does not respect "author" as a quoted string and will regardlessly try to use author for context lookups. I like shlex splitting because it handles quoted strings w/ spaces nicely, but I think the native tags parser should be tweaked a bit to allow for this edge case. I can change from using shlex to using regular string splitting and it fixes the above problem, but at the same it breaks the tests which rely on "quoted strings with spaces." The fix for this whole mess is writing a better parser, but im feelin just way too lazy at the moment to undertake it. Sigh... maybe for v0.4

justquick avatar May 14 '10 10:05 justquick

btw it didnt make it into v0.4

justquick avatar Jun 11 '10 02:06 justquick