I am making an E commerce site, I want to store Cart elements in an integer Array Field. I am using PostGreSql as my database. I have created model for cart by extending Django User model. Here is my models

我正在创建一个电子商务站点,我想将Cart元素存储在一个整数数组字段中。我使用PostGreSql作为数据库。我通过扩展Django用户模型创建了购物车模型。这是我的模型

class UserCart(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    user_product=models.IntegerField(blank=True, null=True)
    cart_products = ArrayField(
        models.IntegerField(blank=True),
        default = list
    )

User.profile = property(lambda u:UserCart.objects.get_or_create(user=u)[0])

Below is my Form.py. I have created only basic form from django import forms from .models import UserCart from django.db import models from django.contrib.postgres.fields import ArrayField

下面是我的Form.py。我只从django的。models导入来自django的UserCart中创建了基本的表单。db从django.programb .postgres导入模型。领域导入ArrayField

class UserCartForm (forms.ModelForm):

    class Meta:
        model= UserCart
        fields = ('user_product',)

I have searched alot on internet but was unable to find the relevant answer.I want that whenever user clicks on Add to Cart button, that product_id gets stored in cart_products array.I read somewhere that ArrayFields behave as list in Django, so here is my views.py

我在网上搜索了很多,但是找不到相关的答案。每当用户单击Add to Cart按钮时,我希望product_id存储在cart_products数组中。我在某个地方读到ArrayFields在Django中表现为list,这是我的view .py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            post.cart_products.append(99)
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

Its giving me Error that

它给了我错误

 AttributeError at /cart/ac/
 'NoneType' object has no attribute 'append'
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    AttributeError
 Exception Value:   
 'NoneType' object has no attribute 'append'
 Exception Location:    C:\Users\Muhammad                
 Jawad\AppData\Local\Programs\Python\Python36-32\mysite\cart\views.py in 
 user_cart, line 19
 Python Executable: C:\Users\Muhammad 
 Jawad\AppData\Local\Programs\Python\Python36-32\python.exe

And if i save cart_products this way

如果我这样保存cart_products

 post.cart_products=99

Then it throws this error

然后它抛出这个错误

 column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    ProgrammingError
 Exception Value:   
 column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.

Kindly Help me in this matter.Summarizing my Question: How can i get user_product as id and save it in cart_products

请在这件事上帮助我。总结我的问题:如何获得user_product作为id并将其保存到cart_products中

2 个解决方案

#1


1

change yor views like this

像这样改变你的观点

views.py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            if post.cart_products:
                post.cart_products.append(99)
            else:
                post.cart_products = [99]
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

更多相关文章

  1. Django的模型。在多个模型类和管理中关联元组
  2. 获取错误“ValueError:int()的无效文字,基数为10:'3128;'在运行Tensor
  3. python之全栈开发——————IO模型
  4. GIS / Gdal / OSGeos在Windows上的django中导入错误
  5. Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标
  6. Hive中使用Python实现Transform时遇到Broken pipe错误排查
  7. 'module'对象没有属性'views' django错误
  8. 数据挖掘(三)分类模型的描述与性能评估,以决策树为例
  9. 机器学习教程之2-k近邻模型的sklearn实现

随机推荐

  1. 如何从Vue.js中的变量名加载组件?
  2. javascript应该注意的小case--操作符
  3. Lua与javascript的差异
  4. 高效地获取XMLhttp对象
  5. 高性能JavaScript代码高亮插件
  6. js“DOM事件”之鼠标事件、js的测试方法
  7. 如何禁用IE和Firefox中的后退按钮? [重复]
  8. ASP.NET文本框不会失去焦点
  9. 如何制作可折叠的bootstrap导航栏?
  10. JavaScript基础练习(一)