GithubHelp home page GithubHelp logo

tymaszweb / django-cookie-law Goto Github PK

View Code? Open in Web Editor NEW
140.0 10.0 70.0 113 KB

Helps your Django project comply with the EU cookie regulations by displaying a cookie information banner until it is dismissed by the user

License: BSD 2-Clause "Simplified" License

Python 69.72% CSS 2.31% JavaScript 7.06% HTML 18.78% Makefile 2.12%

django-cookie-law's Introduction

django-cookie-law

django-cookie-law will display a dismissable banner, making your users aware of cookies being used.

Warning

This app is known to be not complaint with the United Kingdom PECR/GDPR. It is your responsibility to find out whether django-cookie-law meets the specific local legal requirements.

Contributions and comments are welcome using Github at: http://github.com/TyMaszWeb/django-cookie-law

Please note that django-cookie-law requires:

  • Django >= 1.8
  • django-classy-tags >= 0.3.0

Installation

  1. pip install django-cookie-law

  2. Add 'cookielaw' to INSTALLED_APPS

  3. Run collectstatic (Django 1.3+) or copy the statics to your media directory

  4. Add cookielaw/js/cookielaw.js to the markup directly or via your asset manager such as django-pipeline or django-compressor

  5. If you're using Django > 1.8, enable 'django.core.context_processors.request' in your TEMPLATES['OPTIONS'] setting, eg.:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.core.context_processors.i18n',
                    'django.core.context_processors.media',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.core.context_processors.static',
                    'django.core.context_processors.tz',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    

If you're using an older version of Django (< 1.8) then you'll want to change the TEMPLATE_CONTEXT_PROCESSORS setting, eg.:

TEMPLATE_CONTEXT_PROCESSORS = (
        'django.contrib.auth.context_processors.auth',
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.request',
        'django.core.context_processors.static',
        'django.core.context_processors.tz',
        'django.contrib.messages.context_processors.messages'
    )

Note

N.b. versions below 1.8 are not officially supported.

Note

If you don't have this setting defined, just add it to your settings module.

  1. {% load cookielaw_tags %} and add {% cookielaw_banner %} template tag where you want to display the cookielaw banner. Best place for this is your 'base' template, so you will have the cookie banner on every page of your website.

Configuration

If you want to use our default template, add cookielaw/css/cookielaw.css to the markup and you should see the cookie law banner at the top of the page until you dismiss it with the button in the top-right. This CSS is Twitter Bootstrap compatible, but chances are, you'll like to adjust it anyway.

To change the markup, just add a template named cookielaw/banner.html and make sure it is loaded before the default template (for example put the django.template.loaders.filesystem.Loader before django.template.loaders.app_directories.Loader and add your new template to any of the TEMPLATE_DIRS).

To change the CSS, just write your own rules and don't include the default stylesheet.

If you want your visitors to be able to reject the cookies, you should setup cookielaw context processor by adding it to TEMPLATE_CONTEXT_PROCESSORS like this:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'cookielaw.context_processors.cookielaw'
)

That will add cookielaw context variable to the template context. That variable is a dict with 3 keys: notset, accepted and rejected, each with true or false value.

Instead of default banner.html template, use rejectable.html one which shows an example of how to reject the cookies (of course, you may change the template to suit your own needs, just take care that you have <div id="CookielawBanner"> container.

In your templates, you can choose to display the banner only for new visitors (case when cookie is not set):

{% load cookielaw_tags %}
{% if cookielaw.notset %}{% rejectable_cookielaw_banner %}{% endif %}

Of course, you may use {% cookielaw_banner %} as well.

Once the visitors accepts or rejects the cookies, you may choose to load or not load the analytics trackers:

{% if cookielaw.accepted %}
    ... the code to load tracker ...
{% endif %}

Bugs & Contribution

Please use Github to report bugs, feature requests and submit your code: http://github.com/TyMaszWeb/django-cookie-law

author:Piotr Kilczuk
date:2013/04/08

django-cookie-law's People

Contributors

adamcharnock avatar andreiavram avatar andrlik avatar farin avatar gagis avatar jaakkotulkki avatar jiloc avatar joansv avatar khink avatar laundromat avatar lmannering avatar naereen avatar piotrkilczuk avatar saily avatar selectnull avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-cookie-law's Issues

KeyError 'request'

Hey guys,

When in the admin, I keep getting KeyError 'request' errors:

File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/cookielaw/templatetags/cookielaw_tags.py", line 18, in render_tag
   if context['request'].COOKIES.get('cookielaw_accepted', False)

Here is my whole traceback:

Internal Server Error: /favicon.ico
Traceback (most recent call last):
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 150, in get_response
   response = callback(request, **param_dict)
 File "./pickmystartup/views.py", line 1324, in page_not_found
   return HttpResponseNotFound(render_to_string('404.html'))
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/loader.py", line 172, in render_to_string
   return t.render(Context(dictionary))
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/base.py", line 148, in render
   return self._render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/test/utils.py", line 88, in instrumented_test_render
   return self.nodelist.render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/base.py", line 844, in render
   bit = self.render_node(node, context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/base.py", line 858, in render_node
   return node.render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 126, in render
   return compiled_parent._render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/test/utils.py", line 88, in instrumented_test_render
   return self.nodelist.render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/base.py", line 844, in render
   bit = self.render_node(node, context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/base.py", line 858, in render_node
   return node.render(context)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/classytags/core.py", line 106, in render
   return self.render_tag(context, **kwargs)
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/cookielaw/templatetags/cookielaw_tags.py", line 18, in render_tag
   if context['request'].COOKIES.get('cookielaw_accepted', False):
 File "/srv/data/web/vhosts/default/local/local/lib/python2.7/site-packages/django/template/context.py", line 70, in __getitem__
   raise KeyError(key)
KeyError: 'request'

Is this related to the use of django-cookie-law or not? Any solution or thought?

Cookie banner rendered in cached pages

Hello,
Thanks for this little app!

I just noticed that the rendering of the banner is evaluated on the template tag. The problem is that in cached pages it can be rendered or not depending on the user who loaded the page when it was not in cache and other users will get the banner or not depending on that and not on the cookie set.
This could be solved rendering always the banner as hidden, and then showing it only if we can't detect the cookie with javascript.

documentation

The docs say:
If you're using Django > 1.8, enable 'django.core.context_processors.request' in your TEMPLATES['OPTIONS'] setting, eg.:

But the django.core.context_processors.request is decapricated in favor of 'django.template.context_processors.request'

Maybe change docs?

Debugging says: Key error request

hello all

i get an erro when start my app with this plugin:
Exception Type: KeyError
Exception Value: 'request’

Django 1.4.7
django.core.context_processors.request enabled

any help is appreciated
Marco

Django 2.2 compatible? OSError: [WinError 123] on Windows

I used this on an older project running Django 2.1. Now, with a new project running Django 2.2 in a Windows environment, I get the following error after adding to installed apps: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''

'cookielaw_banner'. Did you forget to register or load this tag?

After upgrading to Django 4.1 and 'django-classy-tags' to 3.0.1 I've stumbled on this error.
I don't know if this has to do anything with my configuration, since I haven't found anything on Django breaking changes when upgrading. I had to change {% cookielaw_banner %} to {% CookielawBanner %} to fix the issue. Ofc I had {% load cookielaw_tags %} on the top of my base.html file.

Cookie “cookielaw_accepted” will be soon rejected

I am getting the following warning message when using Firefox:

Cookie “cookielaw_accepted” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite

The error is apparently in this line in the JavaScript code:

document.cookie = name + "=" + value + expires + "; path=/";

Thanks in advance.

2021-03-13_12-25

GDPR compliance

Banners that can only be dismissed aren't compliant with GDPR. Are there any plans to augment this plug-in to make it compliant and ask for consent (opt-in) ?

Override translation

Not sure if this is an issue for django-cookie-law or Django in general, but I'm totally at a loss here...

Problem:

  • I'd like to edit some of the translations in django-cookie-law but despite adding translations for COOKIE_INFO_HEADER etc. to my own .po file (and running compilemessages of course, I keep seeing the translations that come with django-cookie-law.

I'm following the same procedure for editing Django admin translations and then it does work, so that makes the problem even more weird.

I could of course change the COOKIE_INFO_HEADER, etc. to something else and make translations for those, which would work, but then I lose the translations for other languages that come with the app and it's obviously a cumbersome solution to copy all those translations and re-tagging them with the new msgids.

doesn't install templates or static dirs

Hi, If I download the tarball I can see the setup & templates directories are there but neither "pip install django-cookie-law" nor a manual "python setup.py install" on the tarball contents seem to install the templates and static dirs. Any ideas?

Do you need this in the setup.py file?

include_package_data = True

Mobile, impossible to hide the popup.

Hi,

Thanks for this plugin ;)

On Safari / Chrome (iOS) or Android Chrome, I can click as many time as I want, the popup will always come back.

On the other hand, sometimes it won't show, I will wait 3min, reload the home page and the popup is back.

Is there any other configuration to take care of?

Many thanks.

Pop up always displaying

Hi,
thank you very much for this plugin, I really love it.

But some people from my work noticed that the popup is always showing and it quickly become annoying, specially on mobile.
Is it something I have to configure from this plugin or do I have to find a solution myself for it ?

Thank you in advance for the time spend on my request,

best regards

"Uncaught ReferenceError: Cookielaw is not defined" with django-pipeline javascript wrapper enabled

Using django-pipeline for static compression, all javascript output is wrapped in an anonymous function, as security measure.

The click on button I agree fire Cookielaw.createCookielawCookie(); and generate the exception Uncaught ReferenceError: Cookielaw is not defined(…)

A chunk of the generated code:

(function(){var e={createCookie:function(e,t,n){var r=new Date,i="";n?(r.setTime(r.getTime()+n*24*60*60*1e3),i="; expires="+r.toGMTString()):i="",document.cookie=e+"="+t+i+"; path=/"},createCookielawCookie:function(){this.createCookie("cookielaw_accepted","1",3650),typeof window.jQuery=="function"?jQuery("#CookielawBanner").slideUp():document.getElementById("CookielawBanner").style.display="none"}}}).call(this);

With 'DISABLE_WRAPPER': Falseon pipeline configuration, all works as expected.

Banner reappears every time a website is refreshed

Hello,

I use django-cookie-law==2.0.3, Django 3.0.5 and django-classy-tags 1.0.0. I also put my banner in the following cookie_banner.html page:

<script src="{% static 'cookielaw/js/cookielaw.js' %}"></script>

<div id="CookielawBanner">
    <div class="cookie-content">
        <div class="row">
            <div class="col-lg-6">
                <div class="cookie-text">
                    <p class="ml-1 small text-gray-900">This website uses cookies to make your experience better.</p>
                </div>
            </div>

            <div class="col-lg-5">
                <div class="cookie-buttons text-right">

                    <a class="btn btn-success btn-icon-split btn-sm" href="javascript:Cookielaw.createCookielawCookie();">
                        <span class="icon text-white-50">
                            <i class="fas fa-check"></i>
                        </span>              
                        <span class="text">Ok, understood</span>
                    </a>
                </div>
            </div>
        </div>

    <div class="close-cookies  border-bottom-success"></div>
    </div>
    </div>

I also call {% load cookielaw_tags %} in my base.html. When I load the website, I get the banner and when pressing "Ok, understood" it disappears. However, after refreshing the page, it re-appears again. Do you have any idea if what is wrong here? Could it be caused by a bug in cookielaw\js\cookielaw.js?

where to copy cookielaw.js

Hi,
I don't understand what means "the markup" in the README.rst file, ie :
4. Add cookielaw/js/cookielaw.js to the markup
or
To change the markup, just add a template named cookielaw/banner.html

I'm using Django 2.2.9, my django app is called AtlasYEB, my project launchyeb and the templates are in templates/application

thanks!
Sara

Uncaught TypeError: jQuery(...).slideUp is not a function

Hi thanks for this awesome package.

I followed all the steps but then when I click on agree, the banner does not slide up as expected. I get the following error message in the console:

Uncaught TypeError: jQuery(...).slideUp is not a function
    at Object.createCookielawCookie (cookielaw.js:19)
    at <anonymous>:1:11

Here are my files and how I linked the js file:

The js file is the same as in the repository:

var Cookielaw = {

    createCookie: function (name, value, days) {
        var date = new Date(),
            expires = '';
        if (days) {
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    createCookielawCookie: function () {
        this.createCookie('cookielaw_accepted', '1', 10 * 365);

        if (typeof (window.jQuery) === 'function') {
            jQuery('#CookielawBanner').slideUp();
        } else {
            document.getElementById('CookielawBanner').style.display = 'none';
        }
    }

};

And these are my scripts in the base.html:

    <!-- Optional JavaScript -->
    <script type="text/javascript" src="static/cookielaw/js/cookielaw.js"></script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
    <script src="https://use.fontawesome.com/b8d759fc4a.js"></script>

Thanks for your help!

Clicking "I agree" button don't hide the cookie-window & how to change text in message?

When I click "I agree" nothing happens, but if I reload the window the warning is gone. Don't work on either mobile or desktop and I tried with various browsers, still same problem - any idea what the issue can be? I don't have any warnings in the browser console.

Also, I'm wondering how to change the text in the warning to my own language? I did a PR with swedish translation but haven't seen any action on it yet.

Thanks.

Versions
django-cookie-law==2.1.1
Django==3.2.9

In my base.html

{% load cookielaw_tags %}


{% if cookielaw.accepted %}
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KZLXQRFD87"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KZLXQRFD87');
    </script>
  {% endif %}

  <script src="{% static 'cookielaw/js/cookielaw.js'%} "></script>


in my settings

added in installed apps

        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django_admin_env_notice.context_processors.from_settings',
                'cookielaw.context_processors.cookielaw'
            ],

pytest-runner uses unsafe setuptools functions

This project requires pytest-runner, which is marked as 'unsafe' by the safety package.

+==============================================================================+
|                                                                              |
|                               /$$$$$$            /$$                         |
|                              /$$__  $$          | $$                         |
|           /$$$$$$$  /$$$$$$ | $$  \__//$$$$$$  /$$$$$$   /$$   /$$           |
|          /$$_____/ |____  $$| $$$$   /$$__  $$|_  $$_/  | $$  | $$           |
|         |  $$$$$$   /$$$$$$$| $$_/  | $$$$$$$$  | $$    | $$  | $$           |
|          \____  $$ /$$__  $$| $$    | $$_____/  | $$ /$$| $$  | $$           |
|          /$$$$$$$/|  $$$$$$$| $$    |  $$$$$$$  |  $$$$/|  $$$$$$$           |
|         |_______/  \_______/|__/     \_______/   \___/   \____  $$           |
|                                                          /$$  | $$           |
|                                                         |  $$$$$$/           |
|  by pyup.io                                              \______/            |
|                                                                              |
+==============================================================================+
| REPORT                                                                       |
| checked 137 packages, using free DB (updated once a month)                   |
+============================+===========+==========================+==========+
| package                    | installed | affected                 | ID       |
+============================+===========+==========================+==========+
| pytest-runner              | 5.3.1     | >0                       | 43313    |
+==============================================================================+
| Pytest-runner depends on deprecated features of setuptools and relies on     |
| features that break security mechanisms in pip. For example ‘setup_requires’ |
| and ‘tests_require’ bypass pip --require-hashes. See also                    |
| pypa/setuptools#1684.                                                        |
| It is recommended that you:                                                  |
| - Remove 'pytest-runner' from your setup_requires, preferably removing the   |
| setup_requires option.                                                       |
| - Remove 'pytest' and any other testing requirements from tests_require,     |
| preferably removing the tests_requires option.                               |
| - Select a tool to bootstrap and then run tests such as tox.                 |
+==============================================================================+

Currently, there is no fix (released) from pytest-runner: pytest-dev/pytest-runner#60.

EDIT: I just noticed this deprecation issue has a section in the README: https://github.com/pytest-dev/pytest-runner#deprecation-notice

KeyError when an exception is raised

When an exception is raised and the tag is rendered the request is not in context. Warning is displayed but I get a KeyError because of the code doesn't return or raise something.

not working

followed all your steps and is not working.

Update Readme for Django 2.0

Please remove 'django.core.context_processors.request' in the readme as this causes an error in Django. I've read that this is obselete now in Django 2.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.