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
- Let a user
- favorite a post
- save the choice (i.e. store it in the related MySQL DB)
- Change the text and look of the button without loading a new page
How would I go about this?
Here is the boilerplate code to start it off:
Django
### 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:
# ...?
HTML Template
<a class="favorite" href="#" title="Like this post">Like?<a>
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:
…