Django 星级评定系统和 AJAX

发布于 2024-10-17 01:31:29 字数 553 浏览 3 评论 0原文

我正在尝试在 Django 网站上实现星级评级系统。

在我的模型中存储评级是排序的,就像在页面上显示分数一样。但我希望用户能够对页面进行评分(基本上从 1 到 5),而无需刷新或更改页面。

我找到了以下内容,并且喜欢这里星星的风格: http:// jvance.com/blog/2008/09/22/JQueryRaterPluginNew.xhtml

目前对javascript和AJAX了解有限。有谁知道如何将上面示例中的星星与 AJAX 和 Django 结合使用,以便在用户选择评级时无需刷新页面即可更新数据库(模型)?

同样重要的是,用户只能投票一次,即他们不允许对一个页面进行两次评分。他们是否已经投票以及他们之前的投票是什么都存储在模型中。但我怎样才能修改星星来显示这一点呢?


因此,如果您知道如何做这些事情,或者更合适的星级图形解决方案,或者任何好的教程......请分享。谢谢。

I am trying to implement a star rating system on a Django site.

Storing the ratings in my models is sorted, as is displaying the score on the page. But I want the user's to be able to rate a page (from 1 to 5 essentially) without a refresh or change of page.

I have found the following, and like the style of the stars here: http://jvance.com/blog/2008/09/22/JQueryRaterPluginNew.xhtml

Currently have a limited understanding of javascript and AJAX. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating?

It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. It is stored in the models whether they have already voted and what their previous vote was. But how would I be able to modify the stars to show this?

So if you know how to do these things, or a more appropriate star rating graphics solution, or any good tutorials... please do share. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

习ぎ惯性依靠 2024-10-24 01:31:29

AJAX 听起来令人恐惧且令人困惑,但事实并非如此。本质上,您想要做的是将一些数据发布到特定的 url/视图组合。有关使用 AJAX 向服务器发送数据的更多信息,请参阅 jQuery.post

#urls
urlpatterns += patterns('',
url(r'^article/rate/', 'article.rate'),

#views 
def rate(request):
    if request.method == 'POST':
       # use post data to complete the rating..

#javascript
$.post("/article/rate", { rating: 3, article: 2 },
    function(data) {
       // success! so now set the UI star to 3
});

据我所知,星级是通过无线电控件和 CSS 生成的。因此,如果您想在页面加载时显示每个用户的当前评级,只需让您的模板使用 checked 选项呈现关联的收音机即可。

AJAX sounds scary and confusing but it doesn't have to be. Essentially what you want to do is post some data to a particular url/view combo. See jQuery.post for more information on using AJAX to send data to the server.

#urls
urlpatterns += patterns('',
url(r'^article/rate/', 'article.rate'),

#views 
def rate(request):
    if request.method == 'POST':
       # use post data to complete the rating..

#javascript
$.post("/article/rate", { rating: 3, article: 2 },
    function(data) {
       // success! so now set the UI star to 3
});

As far as I know, star-ratings are produced with radio controls and css. So if you want to show the current rating per user on load of the page, just have your template render the associated radio with the checked option.

入怼 2024-10-24 01:31:29

乔纳森,欢迎您来到 django 世界。由于 Django 是一个很酷的框架,一些 djangonauts 编写了很好的网站来帮助我们。

如果您转到 http://djangopackages.com/categories/apps/ 并搜索“评级”你会发现一些 django 可插拔的示例,对你的项目有很大帮助。

另请参阅另一个问题中的实用答案:最佳实践:如何在 Django 模板中最好地实现评级星级

Jonathan you are welcome to the django world. as Django is a cool framework some djangonauts have written nice sites to help us.

if you go to http://djangopackages.com/categories/apps/ and search "rating" you will find some django pluggables with examples that will help you a lot with your project.

also see those util answers in another question: Best Practices: How to best implement Rating-Stars in Django Templates

禾厶谷欠 2024-10-24 01:31:29

最近正在研究这个问题,所以我想我会提供一个混合解决方案。首先,我使用 RateIt,我发现它的设置非常简单,使用起来也非常直观(添加 RateIt *.js.*css 文件到您的 base.html 模板):

http://www. radioactivethinking.com/rateit/example/example.htm

以下是我的解决方案的关键部分:

urls.py

url(r'^object/rate/

my_template.html

<div class="rateit" data-rateit-resetable="false">Rate it!</div>

ajax.js

$('.rateit').bind('click', function(e) {

    e.preventDefault();

    var ri = $(this);
    var value = ri.rateit('value');
    var object_id = ri.data('object_id');

    $.ajax({
        url: '/object/rate/?xhr',
        data: {
            object_id: object_id,
            value: value
        },
        type: 'post',
            success: function(data, response) {
            console.log("ajax call succeeded!");
        },
            error: function(data, response) {
            console.log("ajax call failed!");
        }
    });
});

一些视图位来自 James Bennett(例如,设置 xhr):

http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax- example-part-1/

views.py

from django.views.generic.base import View
from .models import MyObject

class RateMyObjectView(View):

    def post(self, request):

        my_object = MyObject.objects.all().last()

        xhr = 'xhr' in request.GET
        star_value = request.POST.get('value', '')

        my_object.score = star_value
        my_object.save()

        response_data = {
            'message': 'value of star rating:',
            'value': star_value
        }

        if xhr and star_value:
            response_data.update({'success': True})

        else:
            response_data.update({'success': False})

        if xhr:
            return HttpResponse(json.dumps(response_data), content_type="application/json")

        return render_to_response(self.template_name, response_data)

models.py

from django.db import models

class MyObject(models.Model)
    score = models.FloatField(max_length=1, default=0)

请记住,这是一个幼稚的解决方案,只需替换最后一个中的当前星级分数对象列表中的项目。这并不理想,因为最好将分数存储为自己的模型并链接到对象。你可以存储它们并进行平均值等计算。我现在正在研究这个,完成后将更新这个答案。

, RateMyObjectView.as_view(), name='rate_my_object_view'),

my_template.html

ajax.js

一些视图位来自 James Bennett(例如,设置 xhr):

http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax- example-part-1/

views.py

models.py

请记住,这是一个幼稚的解决方案,只需替换最后一个中的当前星级分数对象列表中的项目。这并不理想,因为最好将分数存储为自己的模型并链接到对象。你可以存储它们并进行平均值等计算。我现在正在研究这个,完成后将更新这个答案。

Working on this recently, so thought I would provide a solution to the mix. Firstly, I'm using RateIt, which I have found to be very simple to set up and quite intuitve to use (add the RateIt *.js and .*css files to your base.html template):

http://www.radioactivethinking.com/rateit/example/example.htm

Here are the key pieces to my solution:

urls.py

url(r'^object/rate/

my_template.html

<div class="rateit" data-rateit-resetable="false">Rate it!</div>

ajax.js

$('.rateit').bind('click', function(e) {

    e.preventDefault();

    var ri = $(this);
    var value = ri.rateit('value');
    var object_id = ri.data('object_id');

    $.ajax({
        url: '/object/rate/?xhr',
        data: {
            object_id: object_id,
            value: value
        },
        type: 'post',
            success: function(data, response) {
            console.log("ajax call succeeded!");
        },
            error: function(data, response) {
            console.log("ajax call failed!");
        }
    });
});

Some view bits are from James Bennett (setting xhr, for example):

http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/

views.py

from django.views.generic.base import View
from .models import MyObject

class RateMyObjectView(View):

    def post(self, request):

        my_object = MyObject.objects.all().last()

        xhr = 'xhr' in request.GET
        star_value = request.POST.get('value', '')

        my_object.score = star_value
        my_object.save()

        response_data = {
            'message': 'value of star rating:',
            'value': star_value
        }

        if xhr and star_value:
            response_data.update({'success': True})

        else:
            response_data.update({'success': False})

        if xhr:
            return HttpResponse(json.dumps(response_data), content_type="application/json")

        return render_to_response(self.template_name, response_data)

models.py

from django.db import models

class MyObject(models.Model)
    score = models.FloatField(max_length=1, default=0)

Keep in mind that this is a naive solution, and simply replaces the current star score in the last item in your object list. It's not ideal, as it would be better to store scores as their own model and link to the object. This was you can store them and do calculations like average, etc. I'm working on this now and will update this answer when I'm finished.

, RateMyObjectView.as_view(), name='rate_my_object_view'),

my_template.html

ajax.js

Some view bits are from James Bennett (setting xhr, for example):

http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/

views.py

models.py

Keep in mind that this is a naive solution, and simply replaces the current star score in the last item in your object list. It's not ideal, as it would be better to store scores as their own model and link to the object. This was you can store them and do calculations like average, etc. I'm working on this now and will update this answer when I'm finished.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文