thornomad / django-hitcount Goto Github PK
View Code? Open in Web Editor NEWDjango hit counter application that tracks the number of hits/views for chosen objects
Home Page: http://django-hitcount.rtfd.org
License: MIT License
Django hit counter application that tracks the number of hits/views for chosen objects
Home Page: http://django-hitcount.rtfd.org
License: MIT License
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.
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
How can i get related_name? My model is Ad
.
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?.
I have more than 1 type of item I'd like to hittcount.
Seems in the code that this is currently undoable.
Any chance of adding this?
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
})
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.
This needs to be fixed; old stuff in there.
hitcount/models.py:8: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes.
from django.contrib.contenttypes import generic
See: https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/
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:
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
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?)
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"';
}
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.
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
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.
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 :)
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
See this comment thread for reasoning. Basically, some folks may want to record hits without using JavaScript.
One possible approach:
object_detail
view that can be used in lieu of the basic object_detail
view ... only ours will attempt to record a HitAdd a comment if you have thoughts to this approach.
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?
First thanks @thornomad for this awesome app.
As docs suggested
HITCOUNT_KEEP_HIT_IN_DATABASE = { 'days': 30 }
But if someone wants to make them permanent ??
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)
How can I use django-hitcount in a spa application that is developed in ember?
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.
:-)
Invalid block tag on line 107: 'get_hit_count_javascript'. Did you forget to register or load this tag?
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
I want to display some objects to user, which has zero hits by user. I don't want to loop through all objects for finding objects which has zero hits. Is there any other solution for that?
I have had a chance to explore this but I have objects listed under HitCounts but they are listed with 0 hits.
This should not be happening. I'll research it.
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_hit_count for [object] within ["days=1"] %}
Regards
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.
It's here:
Need to remove it or, better yet, only show it when DEBUG=TRUE
.
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.
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)
...
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
Found your nice piece of code; One problem thought, no Multilingual support.
I'll be happy to contribute it.
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.
Hi.
I followed http://blog.damontimm.com/django-hitcount-app-count-hits-views/ but I get error like:
Caught NoReverseMatch while rendering: Reverse for 'hitcount_update_ajax' with arguments '()' and keyword arguments '{}' not found.
Any hints?
Kind regards,
Rok
Getting RuntimeWarning: DateTimeField received a naive datetime. This is when TZ=True and TIMEZONE=None
I would like to request an enhancement to make the app datetime aware.
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#code
setup.py references to README, but the file is called README.md
del actions['delete_selected'] from line 35 in the admin.py causes following error:
KeyError at /admin/hitcount/hit/
delete_selected
views:20
session_key = request.session.session_key
In normal operation the Hit.delete(save_hitcount=True) would never run. Only if you did it programatically or via the django/python shell. Did you have something in mind for it that I'm missing?
Thanks man
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
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!
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 :)
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.
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
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).
got my model inherit from HitCountMixin
calling mymodel.hit_count.hits always cause this error:
'function' object has no attribute 'hits'
any suggestion, please?
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)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.