我正在製作電子商務網站,我想將Cart元素存儲在整數數組字段中。我使用PostGreSql作爲我的數據庫。 我已經通過擴展Django用戶模型創建了購物車模型。這裏是我的模型如何在Python 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])
下面是我的Form.py.我從Django的進口形式 從.models只創造了基本形式 從django.db進口車型導入UserCart 從django.contrib.postgres.fields導入ArrayField
class UserCartForm (forms.ModelForm):
class Meta:
model= UserCart
fields = ('user_product',)
我已經搜索了很多互聯網上,但爲無法找到相關answer.I想,只要用戶點擊加入購物車按鈕時,得到的product_id存儲在cart_products array.I某處讀取ArrayFields表現爲在Django列表,所以這裏是我的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)
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)
它的給我的錯誤
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
如果我救cart_products這樣
post.cart_products=99
然後拋出這個錯誤
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.
請幫我在這matter.Summarizing我的問題: 我如何獲得user_product作爲id並將其保存在cart_products中
你可以在終端的'cart_products'中附加值嗎? – Bijoy
是的,我已經嘗試過,給出了同樣的錯誤 –