(Django / HTML)如何创建添加到收藏夹功能

时间:2017-05-23 03:54:29

标签: javascript jquery python django

我尝试创建“添加到收藏夹”功能,到目前为止,我设法显示一个带有图标的按钮,该图标基于字段is_favorite,但我无法更新数据库。< / p>

我的问题是:如何在不刷新页面的情况下更改收藏状态并将其更新到我的数据库

编辑 [已解决] 感谢@Nazkter和Bucky Robert的一个项目。我编辑了下面的工作代码

这是我的代码:

model.py

class ProjectProfile(models.Model):
    project_name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    is_favorite = models.BooleanField(default=False)

    def __str__(self):
        return self.project_name

views.py

def index_view(request):
    context = {
        "table_list": ProjectProfile.objects.all(),
        "title": "Table_List"
    }
    return render(request, 'index.html', context)


def favorite_project(request, projectprofile_id):
    projectprofile = get_object_or_404(ProjectProfile, pk=projectprofile_id)
    try:
        if projectprofile.is_favorite:
            projectprofile.is_favorite = False
        else:
            projectprofile.is_favorite = True
        projectprofile.save()
    except (KeyError, ProjectProfile.DoesNotExist):
        return JsonResponse({'success': False})
    else:
        return JsonResponse({'success': True})

url.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', index_view, name='index_view'),
    url(r'^(?P<projectprofile_id>[0-9]+)/favorite_album/$', favorite_project, name='favorite_project'),
]

的index.html

<head>
    <meta charset="UTF-8">
    <title>Favorite function</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Favorite Function</h1>

 <table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Artist</th>
            <th>Favorite</th>
        </tr>
    </thead>
    <tbody>
        {% for data in table_list %}{% csrf_token %}
            <tr >

                <td>{{data.project_name}}</td>
                <td>{{data.artist}}</td>
                <!-- Favorite Album -->
                <td><a href="{% url 'favorite_project' data.id %}"  class="btn btn-default btn-sm btn-favorite" role="button"><span class=" glyphicon glyphicon-star {% if data.is_favorite %}active{% endif %}" action=""></span></a></td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>

的javascript

var ProjectListPage = {
    init: function() {
        this.$container = $('.project-container');
        this.render();
        this.bindEvents();
    },

    render: function() {

    },

    bindEvents: function() {
        $('.btn-favorite', this.$container).on('click', function(e) {
            console.log('Hola');
            e.preventDefault();

            var self = $(this);
            var url = $(this).attr('href');
            $.getJSON(url, function(result) {
                if (result.success) {
                    $('.glyphicon-star', self).toggleClass('active');
                }
            });

            return false;
        });
    }
};

$(document).ready(function() {
    ProjectListPage.init();
});

1 个答案:

答案 0 :(得分:2)

您可以在Django服务器中对某种服务进行ajax调用。

首先,你需要制作一个网址来获取ajax请愿书(urls.py):

url(r'^ajax_is_favorite/$', views.ajax_is_favorite, name='ajax_is_favorite'),

接下来,您需要添加一个功能来解析请愿(views.py):

def ajax_is_favorite(request):
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])
    else:
        #Here you have to get the data and update the object
        return HttpResponse({"success":True})

最后,您需要在模板中创建一个ajax函数来调用服务:

$.ajax({
    url : "{% url 'ajax_is_favorite'%}",
    data: {
        'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
        'ProjectProfileID': 'here you get the id',
        'isFavorite':true //or false
    },
    type : 'POST',
    dataType : 'json',
    success : function(json) {
        if(json.success === true){
            // do somthing
        }else{
            // do somthing
        }
    }
});

不要忘记在模板中添加{%csrf_token%}标记,这是请求的必要条件。