Reputation: 5725
I am simply trying to create a button or link in Django that when clicked will increment a model.IntegerField, but so far have been awfully confused. I understand that I must AJAX-ify this process. I tried using Dajaxice
but ended up running into many troubles.
What is the accepted way to do this? Thanks!
So far I'm just following Dajaxice's tutorial.
My base.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> {% load dajaxice_templatetags %}
My Blog {% dajaxice_js_import %}
<script type="text/javascript">
function my_js_callback(data){
if(data==Dajaxice.EXCEPTION){
alert('Error! Something happens!');
} else {
alert(data.message);
}
}
</script>
</head>
<body>
<h1><a href=””>My Blog</a></h1>
{% block content %}{% endblock %}
</body>
Within that block content I have <a href="" onclick="Dajaxice.example.myexample(my_js_callback);">Click me!</a>
this code {% dajaxice_js_import %}
generates <script src="/dajaxice/dajaxice.core.js" type="text/javascript" charset="utf-8"></script>
which is just http://localhost:8000/dajaxice/dajaxice.core.js
So far the problem is that that file can not be found, and yet I have placed it under /templates/dajaxice/
Not sure what to do. Thanks!
Edit after mention of static files
So it looks like I am not placing my static files correctly. I followed the instructions atDjango's docs how to serve static files
Let me know if I did this right. I have created a folder "static" under "myProject/static". I have placed my JS files within static/ For example "myProject/static/prototype.js"
I also have STATIC_URL='static'
and 'django.contrib.staticfiles',
in INSTALLED_APPS
I now try to grab prototype.js using <script type="text/javascript" src="{{ STATIC_URL }}prototype.js"/>
but still no avail...
What am I doing wrong now? Thank you! *Edit:*looks like /static/ should be inside the app folder. How confusing...
Upvotes: 1
Views: 823
Reputation: 38382
Remember to do it atomicly:
# models.py
class Page(models.Model):
hits = models.PositiveIntegerField()
# views.py
def hit(request, page_pk):
Page.objects.filter(pk=page_pk).update(hits=F('hits')+1)
return HttpResponse()
…or use a transaction:
# views.py
from django.db.decorators import commit_on_success
@commit_on_success
def hit(request, page_pk):
page = Page.objects.filter(pk=page_pk)
page.hits += 1
page.save()
return HttpResponse()
Upvotes: 2