django-cookie-consent icon indicating copy to clipboard operation
django-cookie-consent copied to clipboard

Empty cookie_consent value after calling /cookies/accept/

Open frollow opened this issue 7 months ago • 0 comments

dic = {'unclassified': '', 'marketing': '', 'statistic': ''}

def dict_to_cookie_str(dic):
    return "|".join(["%s=%s" % (k, v) for k, v in dic.items() if v]

The result is that the function returns the empty string because the if v condition in the list generator excludes any key-value pairs where the value is the empty string.

The issue arises when /cookies/accept/ is called, and the cookie_consent remains empty. As a result, we can never set parameters for /cookies/accept/.

The problem with your dict_to_cookie_str(dic) function is that the values in your dictionary dic are empty (empty strings). Consequently, the function returns an empty string because the condition if v in the list comprehension excludes any key-value pairs where the value is an empty string.

How the function works:

  • %s=%s % (k, v): This part formats each key-value pair into a string, for example, key=value.
  • for k, v in dic.items(): This iterates over each key-value pair in the dictionary dic.
  • if v: This condition checks whether the value v is truthy. In Python, an empty string ('') evaluates to False, so if the value is an empty string, it will not be included in the final list.

Example:

For your dictionary dic = {'unclassified': '', 'marketing': '', 'statistic': ''}, each value is an empty string, so the condition if v is not satisfied for any element, and the list comprehension returns no elements. As a result, the function returns an empty string after executing the join() method.

Solutions:

  1. Change the condition: If you want to include all keys in the resulting string, regardless of whether their values are empty, remove the if v:
def dict_to_cookie_str(dic):
    return "|".join(["%s=%s" % (k, v) for k, v in dic.items()])
  1. Data correction: If empty values should be excluded, ensure that your dictionary contains significant (non-empty) values before calling the function. For example:
dic = {'unclassified': '1', 'marketing': '1', 'statistic': '1'}
### Tasks
- [ ] https://github.com/jazzband/django-cookie-consent/pull/129

frollow avatar Jun 29 '24 06:06 frollow