简体   繁体   English

使用带有Django,Ajax和Jquery的复选框,一次将一项添加到“购物车”中

[英]Add items one at a time to a “cart” using checkboxes with Django, Ajax, and Jquery

New code now included, but still not working... 现在已包含新代码,但仍然无法使用...

I am trying to use checkboxes to select an item(s) an add it to the "cart" at the top of the page. 我正在尝试使用复选框来选择一个项目,然后将其添加到页面顶部的“购物车”中。 Every item on the page has a checkbox next to it that, when selected, should add the item to the cart and display that item name in the "cart" section at the top of the page. 页面上的每个项目旁边都有一个复选框,选中该复选框后,应将其添加到购物车中,并在页面顶部的“购物车”部分中显示该项目名称。 So, as the user goes down the page and checks an item, I want that item name to appear in the "cart" section at the top of page. 因此,当用户浏览页面并检查项目时,我希望该项目名称出现在页面顶部的“购物车”部分中。

(ie check an item and the item name appears at top of page; check another item and that item name appears beside the first item at the top of the page; etc.) (即检查一个项目,项目名称显示在页面顶部;检查另一个项目,该项目名称显示在页面顶部的第一个项目旁边;等等。)

With previous versions of my code, I have been able to get the first item listed on the page (and only the first item) to actually show in the "cart" section. 使用我的代码的早期版本,我已经能够获取页面上列出的第一项(只有第一项),以实际显示在“购物车”部分中。 I have tried everything I can, but I am completely new to Django, Ajax, and Jquery. 我已经尽力了,但是我对Django,Ajax和Jquery完全陌生。 Can someone please help!? 有人可以帮忙吗? Thank you! 谢谢!

"cart" section of list.html: list.html的“购物车”部分:

    <div id="programCart">
        <table cellpadding="5" cellpadding ="2" border="2" id="selected_programs_cart">
            <tbody>
                <tr>
                <td id="selectionsHere"> SampleSelection1 </td>
                </tr>
            </tbody>
        </table>    
    </div> 

html that lists the items with a checkbox next to each, part of list.html (these items are displayed with a larger 'for' loop): 列出项目的html,在list.html的每个部分旁边都有一个复选框(这些项目显示为较大的“ for”循环):

<td>
<form id="programs-selected" method="GET" action="select_citations">
    <script type="text/javascript" src="/static/js/citations.js"></script>
    <ul>
        <li><input type="checkbox" id="programCheckbox" name="programs_to_add" value="{{software.id}}" />
        </li>
    </ul>
</td>
</form>

selectitems.js: selectitems.js:

$('#programCheckbox').click(function(){
    var softwareID
    softwareID = $(this).attr("value")

    $.get('add_to_cart', function(data){
        $tbody = $("selected_programs_cart").find('tbody');
        $.each(data, function(){
            var displayCart = json.addingToCart;
            for (var key in displayCart)
                if (key == 'cart'){
                    var value = displayCart[key];
                    for (var softwareName in value)
                        $("<td>" + softwareName + "<td>").appendTo($tbody);
            };
        });
    });
});

itemview.py itemview.py

def add_to_cart(request):
#dict of 'cart' to list of selected programs to return
to_JSON = {}

#Programs are already in the cart and the "cart" key already exists in the session-
if 'cart' in request.session:
    logger.warning("cart found")
    software_id = request.GET.get('softwareID')
    softwareObject = Software.objects.get(pk='software_id')
    softwareName = softwareObject.title

    addingToCart = request.session.get('cart')
    request.session['addingToCart'].append(softwareName)

    to_JSON = request.session['addingToCart']

#first time clicking on a program, no existing cart in session: the session should store 'cart' as the key and a list of selected programs as the value
else:
    logger.warning("cart not found")
    #get the softwareID of the most recently clicked program
    software_id = request.GET.get('softwareID')
    if software_id == None:
        #oops, can't retrieve this from the request
        logger.warning("cannot find software_id in the request")
        return HttpResponse(request) # TODO: there's probably a better way to handle this
    else:
        logger.warning( "request.GET.get('softwareID'): {}".format(request.GET.get('softwareID')) )
        try:
            softwareObject = Software.objects.get(pk='software_id')
        except Software.DoesNotExist as e:
            logger.warning("oh oh, Someone is trying to access a Software ID that doesn't exist: {}".format(e))
            # TODO: what to do if this happens?
        except ValueError as e:
            logger.warning("oh dear: {}".format(e) )

            #TODO: if an exception happens, the softwareObject won't exist, what should happen then?
        softwareName = softwareObject.title

        #create an entry in the session dictionary for the cart and program list
        request.session['cart'] = []

        #add the first selected program to the list
        request.session['cart'].append(softwareName)

        addingToCart = request.session['cart']
        to_JSON = request.session['addingToCart']

response_data = json.dumps(to_JSON)
return HttpResponse(response_data, content_type='application/json')

#return HttpResponse(json.dumps(cart, ensure_ascii=False), content_type='application/json')

This question is fairly broad, and will most likely get closed or downvoted out of existence, but I thought I'd try to steer you in the right direction. 这个问题相当广泛,很可能会被关闭或被淘汰,但是我想我会尽力引导您朝着正确的方向发展。

Your view function is pretty far from being able to return JSON that your jQuery method can consume and use to update the DOM. 您的视图函数远不能返回jQuery方法可以使用并用于更新DOM的JSON。 Here's some pseudo-code: 这是一些伪代码:

import json

from django.http import HttpResponse

# or if you're using Django 1.7, you can use the JsonResponse class:
# https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects

from your_app.models import Software


def add_to_cart(request):
    # get an existing cart from the request
    cart = request.session.get('cart', {'items': []})

    # get the objects for the ids in the request
    software_ids = request.GET.getlist('software_ids')
    software = Software.objects.filter(id__in=software_ids)

    # append the items to the cart
    cart['items'].append(software)

    # set the cart into session so you can persist it across requests
    request.session['cart'] = cart

    # dump the cart to JSON and send back a the response
    return HttpResponse(json.dumps(cart, ensure_ascii=False),
        content_type='application/json')

Something important to keep in mind here is that anything you want to put into session has to be serializeable to a string. 这里要记住的重要一点是,要放入会话中的任何内容都必须可序列化为字符串。 The jsonpickle module is great for encoding/decoding complex Python objects to JSON. jsonpickle模块非常适合将复杂的Python对象编码/解码为JSON。

Keeping concerns separate, you might want to pass the data returned from the response to a JavaScript templating function, like Underscore 's _.template() and pass it the data from the response, rather than return HTML from the view. 保持关注分开,你可能想通过从响应返回给一个JavaScript模板功能,如数据下划线_.template()和响应传递给它的数据,而不是从视图返回HTML。

There are also pre-made carts for Django: django-cart and django-carton . 还有针对Django的预制购物车django-cartdjango-carton There's also this comparison chart of Django e-Commerce packages. 还有Django电子商务软件包的比较表 Hope that gets you going. 希望你能走。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM