GithubHelp home page GithubHelp logo

thornomad / django-hitcount Goto Github PK

View Code? Open in Web Editor NEW
462.0 462.0 187.0 335 KB

Django hit counter application that tracks the number of hits/views for chosen objects

Home Page: http://django-hitcount.rtfd.org

License: MIT License

Python 90.33% HTML 6.18% JavaScript 3.50%

django-hitcount's Introduction

django-hitcount's People

Contributors

applecat avatar bashu avatar dependabot[bot] avatar dulacp avatar fabiant7t avatar gabipurcaru avatar harshulj avatar jan-matejka avatar kelketek avatar mapeveri avatar mateusz800 avatar maxg0 avatar piecio avatar pjhoberman avatar q0w avatar se0kjun avatar sebslomski avatar sirsaleh avatar stasfilin avatar thornomad avatar timgates42 avatar xfreon avatar zengqiu 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-hitcount's Issues

int() argument must be a string, a bytes-like object or a number, not 'property'

So, I'm sure I'm doing something wrong but I can't figure out what.

I've been following the docs and this is what I have so far:

  • pip install...
  • settings.py with 'hitcount'
  • then on views.py (my model is named Artigo):
    hit_count = HitCount.objects.get_for_object(Artigo)

This line is giving me the error from the issue title:
int() argument must be a string, a bytes-like object or a number, not 'property'

I haven't done anything else than this. What am I missing?
I've also tried doing class Artigo(models.Model, HitCountMixin): but then when I try to makemigrations I get No changes detected

Working with nosql db

I realized that it's not working with nosql dbs properly. Uniqueness of the hit_count object cannot be determined, results in having lots of hit_count objects around. One needs to write some unit tests to solve this issue for different db backends. I am afraid I won't have time to fix this bug on my own.

jQuery in no conflict mode

Hi,

I'm using django-hitcount and I'm very satisfied (thanks for your work), but I have a problem with jQuery since my website is using prototype and scriptaculous for all my js/ajax needs. I have a conflict problem when importing the 3 frameworks (prototype, scriptaculous and jquery), either jquery or the scriptaculous/prototype couple is not working, depending on my import order.

Would it be possible to use jQuery in no conflict mode to be able to use django-hitcount (and so jquery) with other majors js frameworks?

I did the following to resolve my conflict problem:

First my head includes
{% load hitcount_tags %}
<script type="text/javascript"></script>

And I changed the following in templatetags/hitcount_tags.py
--- a/hitcount/templatetags/hitcount_tags.py
+++ b/hitcount/templatetags/hitcount_tags.py
@@ -153,7 +153,7 @@ class GetHitCountJavascript(template.Node):
obj, created = HitCount.objects.get_or_create(content_type=ctype,
object_pk=object_pk)

-        js =    "$.post( '" + reverse('hitcount_update_ajax') + "',"   + \
+        js =    "jQuery.post( '" + reverse('hitcount_update_ajax') + "',"   + \
                 "\n\t{ hitcount_pk : '" + str(obj.pk) + "' },\n"         + \
                 "\tfunction(data, status) {\n"                         + \
                 "\t\tif (data.status == 'error') {\n"                  + \
@@ -172,7 +172,7 @@ def get_hit_count_javascript(parser, token):

     <script src="/media/js/jquery-latest.js" type="text/javascript"></script>
     <script type="text/javascript"><!--
-    $(document).ready(function() {
+    jQuery(document).ready(function() {
         {% get_hit_count_javascript for [object] %}
     });
     --></script> 

Thanks.

{% get_hit_count for [object] within ["days=1,minutes=30"] %} not working

Hi,

I am using django 1.10 with django-hitcount and can't use this exmaple from the docs:
{% get_hit_count for building %}
This is working, but if i add the within statement I got this error:
{% get_hit_count for building within ["days=1,minutes=30"] %}
Template Error:

invalid literal for int() with base 10: '1]'

Any idea what could be wrong? Without the "within" statement, everythink works fantastic :)

Hit Admin error

del actions['delete_selected'] from line 35 in the admin.py causes following error:

KeyError at /admin/hitcount/hit/
delete_selected

advice: my website is visit for 100k

Hi, when this happend 100k visit this site
When the visits are strong, the site gets super slow, I think the apps start writing to the database and that causes slowness
What can I do for the 10k in a few minutes? and databases writen and not slow down the site?
What advice do you give me?

GDPR compliance

Hi, I really like this django add on. However, I've noticed that it has a feature of max hits per IP address, which makes me think that the app tracks hits by IP (i'm yet to go through the source code).

Without asking for permission to track a user by their IP address, this goes against GDPR.

Would it be possible to do with the Session ID cookie instead / is this what it already uses?

Thanks in advance

Using hitcount in Generic ListView

How to use hitcount in generic list view. I can't figure it out it pops up quite a few errors.
I got a generic DetailView and it works perfectly fine for it. But for generic ListView it does not simply work for me. I just need to set it up for a list and need to be able to see 6 products with most views.
Your help is appreciated for creating nice and needful piece of code but if you can help to solve this problem it will be a great help.
Cheers.
:-)

Installs as an egg

Seems like django-hitcount installs as an egg? That does not work so well with django, which by default, expects template files to exist in real directories. A non-egged install option would be preferable.

Give back the maintainer right

Hi,

This repository seems to lack maintenance, I propose myself as a new maintainer.

Could you give me the right to push in your repository or just transfer it on my account in github?

Thank you

Rest-API

Hi Dear,
How can i use hit-count in my rest API's
I am using detail_route

my code is given below
class BookViewSet(viewsets.ModelViewSet):

queryset = Book.objects.all()
serializer_class = BookSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)

@detail_route(renderer_classes=(renderers.StaticHTMLRenderer,))
def perform_create(self, serializer):
    serializer.save(owner=self.request.user)

Create relationship with hitcount

I want to create a relationship using my own model with hitcount model, so I can filter on the hitcount numbers with Django Filtering, such as annotate().filter()

get @Property from HitCountMixin seems not working to implement that.

Thanks

README

ok, so it's not really an issue...but if you name your readme file "README.rst" then github will parse it and display it prettily :)

How to sort my products based on your hitcount package?

I have used your hit count package in my project. But i am unable to get the hitcounts per product in my views. The main reason that i want to get hit counts is that i want to sort my products based on hit counts.
Yes! There is a different model named "hitcounts" in admin view that shows the total hit. but how can i sort a different model products based on this "hitcount" model?
My code:

class Product(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
title = models.CharField(max_length=250)
description = models.CharField(max_length=500)
hit_count_generic = GenericRelation(
HitCount, object_id_field='object_pk',
related_query_name='hit_count_generic_relation')

def get_absolute_url(self):
    return reverse('products:detail',
                  kwargs={'product_id': self.pk})
def __str__(self):
    return self.title + ' - ' + str(self.id)

Django 1.7 Migrations error

On test builds, is failing with this error:

KeyError: u"Migration hitcount.0001_initial dependencies reference nonexistent parent node (u'contenttypes', u'0002_remove_content_type_name')"

Not sure where that dependency came from or why only 1.7 and not 1.8.

ValueError: invalid literal for int() with base 10

When my model has a pk that is a string, the call hit_count = HitCount.objects.get_for_object(obj) fails with invalid literal for int() with base 10: 'blablabla'

I suppose django hit count is not adapted to strings

Non-ajax hit recording approach (based on UA list)

See this comment thread for reasoning. Basically, some folks may want to record hits without using JavaScript.

One possible approach:

  • implement a way to import a list of bot User-Agents into our banned UA database (we are already checking that database as it is)
  • create our own wrapper for an object_detail view that can be used in lieu of the basic object_detail view ... only ours will attempt to record a Hit

Add a comment if you have thoughts to this approach.

Internationalization !

Found your nice piece of code; One problem thought, no Multilingual support.

I'll be happy to contribute it.

Installation error after Syncdb

File "/home/dhar/envs/at_env/local/lib/python2.7/site-packages/hitcount/models.py", line 11, in
from django.contrib.contenttypes.fields import GenericForeignKey
ImportError: No module named fields

'function' object has no attribute 'hits'

got my model inherit from HitCountMixin
calling mymodel.hit_count.hits always cause this error:
'function' object has no attribute 'hits'

any suggestion, please?

DataError: invalid byte sequence for encoding "UTF8": 0xf1 0x61 0x3b 0x46

...
    hit_count_response = HitCountMixin.hit_count(request, hit_count)
  File "project/.venv/local/lib/python2.7/site-packages/hitcount/views.py", line 54, in hit_count
    if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
  File "project/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 170, in __nonzero__
    return type(self).__bool__(self)
  File "project/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 166, in __bool__
    self._fetch_all()
  File "project/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "project/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "project/.venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "project/.venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "project/.venv/local/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "project/.venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
DataError: invalid byte sequence for encoding "UTF8": 0xf1 0x61 0x3b 0x46

The HTTP_USER_AGENT was:

Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13B143 [FBAN/FBIOS;FBAV/87.0.0.44.70;FBBV/54482584;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iPhone OS;FBSV/9.1;FBSS/2;FBCR/OrangeEspa\xf1a;FBID/phone;FBLC/de_DE;FBOP/5;FBRV/55128799]

It's a Python 2 with Postgres installation and:

Django==1.8.17
django-hitcount==1.2.2

created_format --

is there a reason you have decided to use a custom created_format funtion instead of the standard. everything else is based of localtime zone in the admin. not sure why you would want this any different.

Counting guest views

Hello,

I have one small problem with your app. It counts only views from authenticated users.

Link for my app: https://github.com/dyzajash/TB_cms/tree/develop
Python version: 2.7.5
Django: 1.8.4

show.html layout:

{% extends "shared/layout.html" %}
{% load staticfiles %}
{% load markdown_filter %}
{% load download_formatter %}
{% load hitcount_tags %}

{% block title %}{{ post.title }}{% endblock title %}

{% block content %}
    <div class="news"> <!-- news -->
        <h1>{{ post.title }}</h1>

        <div class="news-views">{% get_hit_count for post %}</div>
        <div class="news-author">{{ post.author }}</div>

        <div class="news-content">
            {% if post.manga %}
                <div class="news-img"><img src="{{ post.manga.news_image.url }}" alt="{{ post.title }}-image"></div>
            {% else %}
                {{ post.content|markdownify|safe }}
            {% endif %}
            <div class="chapters"><!-- chapters -->
                {{ post.download|blob_to_html|safe }}
            </div>
            <!-- chapters -->

            {% if user.is_authenticated %}
                <a href="{% url 'edit-news' post.slug %}" class="red-button">Edytuj</a>
            {% endif %}
            <a href="{% url 'home' %}" class="gold-button">Wróć</a>
        </div>
    </div> <!-- news -->
{% endblock %}
{% block extra_scripts %}
    <script src="{% static 'hitcount/hitcount-jquery.js' %}"></script>
    {% insert_hit_count_js_variables for post %}
{% endblock %}

settings (as base.py):

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sitemaps',
    'django.contrib.sites',
    'django_forms_bootstrap',
    'hitcount',
)

PROJECT_APPS = (
    'accounts',
    'api',
    'blog',
    'dashboard',
    'projects',
    'utils'
)

INSTALLED_APPS += PROJECT_APPS
SESSION_SAVE_EVERY_REQUEST = True

and nginx conf:

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }

Support for Non-int object_pk values?

Currently, non-integer object_pk values are not supported, right? In my application I'm using UUID values instead of PositiveInteger values for primary keys, and something seems to be unhappy with this, so I'm just checking whether it's expected.

e.g. it tries to insert, for each of these fields respectively:

[<django.db.models.fields.PositiveIntegerField: hits>,
 <django.db.models.fields.DateTimeField: modified>,
 <django.db.models.fields.related.ForeignKey: content_type>,
 <django.db.models.fields.PositiveIntegerField: object_pk>]

(0,
 datetime.datetime(2015, 11, 8, 14, 59, 26, 846708, tzinfo=<UTC>),
 18,
 529346511985444997385400981615289)

Feature request: Show hits from yesterday, lastweek ...

Hi,

how can I check hits for a specific time period? Right now, it is only possible to count the hits from now back to a certain time period.

Get total hits for an object over a certain time period:

{% get_hit_count for [object] within ["days=1"] %}

Regards

On delete cascade

Is posible add on_delete=models.CASCADE to model HitCount:

  @python_2_unicode_compatible
   class HitCount(models.Model):
        ...
        content_type = models.ForeignKey(
            ContentType, related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE)

For remove automatic in model HitCount when occurs on delete event in model parent?.

Thanks!

Blank ?

Why is it not showing any data but blank?
screen shot 2017-06-16 at 20 30 31

Sort by amount of views

Hello. I'm trying to implement a sorting by an amount of views. Is it possible with your app? Thanks in advance.

Piece of my code:

    def get(self, request, *args, **kwargs):
        user = request.user
        entries = Entry.objects.all().order_by('-date') #i need amount of views here

        return render(request, path/to.html', context={
            'entries': entries,
            'user': user
        })

wrong user's repo for pip installation

pip install -e git://github.com/ariddell/django-hitcount.git#egg=django-hitcount

should be

pip install -e git://github.com/thornomad/django-hitcount.git#egg=django-hitcount

Cron job to cleanup "old" Hit objects

We should have a simple cron utility that can cleanup expired Hit objects when they get too old (user defined as to when they are considered old).

always get zero hitcount

I installed hitcount amd followed your installation guide. Everything is fine except that all hitcount mever increase and show 0. That is, if someone click tje countable page, this page will appear in the admin list, but with the number 0.

Update requirements

Is this project compatible with django-1.10? If so, we should change the package requirements to be django<1.11 instead of django==1.9.6. The requires.io badge shows the insecure label because of that.

ImportError in django 1.5

I have to use django 1.5 for a project because it uses django-postman. I installed hitcount like this:
pip install -e git://github.com/thornomad/django-hitcount.git#egg=django-hitcount

Here's what I get:

File "/home/.../src/django-hitcount/hitcount/models.py", line 11, in <module> from django.contrib.contenttypes.fields import GenericForeignKey ImportError: No module named fields
How can I get an older version?.

hitcount_cleanup does not work in 1.8

1.8 changed something with the transactions:

Traceback (most recent call last):
  File "../../django-hitcount/hitcount/management/commands/hitcount_cleanup.py", line 21, in handle_noargs
    transaction.commit_unless_managed()
AttributeError: 'module' object has no attribute 'commit_unless_managed'

Need to fix that -- broken for now.

Missing on_delete argument in ForeignKey fields

Django 2.0 requires ForeignKey fields to explicitly define the deletion behavior. Using hitcount with Django 2.0 therefore fails when applying migrations:

  File "/home/mde/.virtualenvs/XXXX-YLXBf2NZ/lib/python3.5/site-packages/hitcount/models.py", line 118, in Hit
    user = models.ForeignKey(AUTH_USER_MODEL, null=True, editable=False)
TypeError: __init__() missing 1 required positional argument: 'on_delete

This can be fixed by simply adding a on_delete=models.CASCADE argument to ForeignKey fields. Should I submit a PR for this? (has the project been tested with Django 2.0? Or should I test it a bit more and maybe submit a larger PR to make it compatible?)

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.