将jquery cookie写入sqlite | localhost django

时间:2015-12-28 22:34:49

标签: jquery django sqlite cookies

将此jquery.cookie写入SQLite数据库的最佳方法是什么? (当然没有形式)

$ .cookie(' cart')=

"[{"name":"Cinnamon bun","image":"/static/images/items/bakery/cinnamon_bun.jpg",
"price":" 5 uah","quantity":"2","alias":"cinnamon"},
{"name":"Croissant","image":"/static/images/items/bakery/croissant.jpg",
"price":" 10 uah","quantity":"1","alias":"croissant"},
{"name":"Donut","image":"/static/images/items/bakery/donuts.jpg",
"price":" 7 uah","quantity":"4","alias":"donut"},
{"name":"Chocolate chip cookies","image":"/static/images/items/bakery/cookies.gif",
"price":" 30 uah","quantity":"2","alias":"cookies"}]"

1 个答案:

答案 0 :(得分:0)

他们有两种可能性:

  1. 使用simple_tag(自定义模板标记)
  2. 多亏了它,您不必担心URL用户将访问哪个。下面写的代码将按照每个请求运行。

    文档HERE。 (注意:它适用于1.8版本,如果您使用的是不同版本的Django,请不要忘记切换文档)。

    您的代码应如下所示:(在templatetags /文件夹中的python文件中)

    @register.simple_tag(takes_context=True)
    def your_name_of_this_function(context):
        """
        What is this tag about? (your comment)
        """
        request = context["request"]
    
        # Get cookies
        cookies = request.cookies["cart"]
    
        # Your codes for writing new lines into your models into your SQlite DB
        # if they are not in DB (the cookies)
        ...
    

    有关请求HERE的更多信息。注意:cookie采用字典

    的形式

    然后将此行添加到顶部的“base.html”:

    {% load your_name_of_your_tag_script_without_dot_py %}
    

    和某处(仍然是“base.html”):(例如)

    {% name_of_your_function_from_that_script %}
    

    正如我所说,这段代码将按照每个请求运行simple_tag。

    1. 在views.py
    2. 中的1个函数中没有simple_tag

      在这种情况下,用户必须点击特定的URL才能将cookie写入数据库。

      代码:

      def your_function(request):
          """
          blablabla
          """
          cookies = request.cookies["cart"]
      
          # Codes for creating a new line into your models
          ...