开发者

A Very, Very Basic JavaScript Button in Django

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(req开发者_JAVA技巧uest, '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:

<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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜