Reputation: 1185
I know a bunch of Django, HTML, and CSS, but I somehow never got around to do anything in JavaScript (only did a little jQuery).
I want to use this on a simple website for the time being for pressed buttons whose look and relevant database changes without reloading the page. I would like a simple example using Django and maybe some jQuery to start learning it.
Let’s just use a Favorite/Like button known from, say, Twitter as an example.
The button has to
How would I go about this?
Here is the boilerplate code to start it off:
### models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
likes = ManyToManyField(User, null=True, blank=True, related_name="likes")
### views.py
def post(request, post_id):
if request.method != 'POST':
render(request, 'mytemplate.html',
{'post': get_object_or_404(Post, pk=post_id)})
else:
# ...?
<a class="favorite" href="#" title="Like this post">Like?<a>
Upvotes: 0
Views: 1616
Reputation: 600051
This isn't really "very, very basic".
For a start, it's Ajax, rather than simple Javascript. Javascript on its own can alter anything on the page, but you want to send something to the server and get a response, which is more complicated - not massively, but enough.
Note that you really need something in your markup to identify the post being liked:
<a class="favorite" id="{{ post.id }}" title="Like this post">Like?</a>
$.ready(function() {
$('.favorite').click(function() {
var $this = $(this);
var post_id = this.id;
$.post('/like/' + id + '/', function() {
$this.replaceWith("<span class='liked'>Liked</span>");
});
});
});
...
if request.is_ajax():
post.likes.add(request.user)
Upvotes: 2
Reputation: 98926
If you were doing this without JavaScript, your favourite button would be a submit button in a form, that submitted to a URL handled by a Django view function that made the required database changes.
To do this via JavaScript, you replace the form submission with some JavaScript code that uses XMLHTTPRequest
to do the POST
instead.
Upvotes: 1