django-page-views
Install
- `pip install django-page-views`
- `pip install djangoip`
Usage
**/settings.py**
python
INSTALLED_APPS += [
"django_page_views",
"djangoip",
]
MIDDLEWARE += ["djangoip.middleware.ip_middleware.IpMiddleware"]
**Migrate**
- `python manage.py makemigrations djangoip`
- `python manage migrate`
**/urls.py**
python
urlpatterns += [
path("django-page-views/", include('django_page_views.urls')),
]
Save a new model and add new ip
python
from django.contrib.contenttypes.models import ContentType
from django_page_views.models import DjangoViews
from myapp.models import MyModel
def increase_ip(request, pk):
content_type_obj = ContentType.objects.get_for_model(MyModel)
dj_query, created = DjangoViews.objects.get_or_create(
content_type=content_type_obj,
object_id=pk
)
try:
dj_query.ips.add(request.ip_model)
except IntegrityError:
pass
**template tags**
{% load django_page_views %}
{{ model|views_count:id }}
Js
js
function get_data(apiUrl){
return fetch(apiUrl)
.then((resp) => resp.json())
.then(function(data) {
return data;
})
.catch(function(error) {
console.log('request failed', error)
});
}
function get_content_views(content_id){
return get_data(`/django-page-views/get-view/app_label/model/id`).then(function(views_data){
try{
var views = views_data[0].views_count;
}
catch(err){
var views = 0;
}
return views
});
}
get_content_views(content_id).then(function(views){
console.log(views)
});