我认识了一帮Django的,HTML和CSS的,但我却从来没有抽时间去在JavaScript中做任何事情(只是做了一个小的jQuery)。
我想用这个在一个简单的网站暂时为pressed按钮的外观和无需重新加载页面相关的数据库更改。我想一个简单的例子使用Django,也许一些jQuery开始学习吧。
让我们只用一个收藏/ Like按钮,比如说,从微博被称为一个例子。
按钮具有
让用户 最喜欢的一个帖子 保存选择(即存放在相关的MySQL数据库) 而无需加载一个新的页面更改按钮的文本和外观我会如何呢?
下面是样板code键启动该功能:
### models.py
从django.db进口车型
从django.contrib.auth.models导入用户
类岗位(models.Model):
喜欢= ManyToManyField(用户,空=真,空白= TRUE,related_name =喜欢)
### views.py
高清职位(要求的post_id):
!如果request.method ='POST':
渲染(要求,mytemplate.html,
{'后':get_object_or_404(邮政,PK =的post_id)})
其他:
#...?
<一类=最喜欢的href =#称号=像这样的职位>像< A>
解决方案
这是不是真的非常,非常基本的。
首先,这是阿贾克斯,而不是简单的JavaScript。 Javascript的自己可以改变页面上的任何东西,但你要送东西到服务器,并得到回应,这是比较复杂的 - 而不是大规模,但足够
请注意,你真正需要的东西在您的标记,以确定岗位被人喜欢:
<一类=最爱ID ={{post.id}}称号=像这样的职位>像< / A>
$。就绪(函数(){
$('。最喜欢的)。点击(函数(){
变量$此= $(本);
VAR的post_id = this.id;
.post的$('/喜欢/+ ID +'/',函数(){
$ this.replaceWith(&所述;跨度类='喜欢'>&顶过其中; /跨度>中);
});
});
});
...
如果request.is_ajax():
post.likes.add(request.user)
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 pageHow 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>
解决方案
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)