我在django中存储数据时遇到了麻烦。我附加一个元组,但每次我发一个帖子请求它都会显示一个空数组。它应该每次都附加?谁能让我知道为什么会这样? (我的表格和数据工作正常,信息在request.POST中收到)
views.py
会话在用户登录时启动
def post(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
request.session['cart'] = []
return redirect("/")
else:
return render(request, 'sign_in.html', {
"error": "Invalid Credentials"
})
现在是
的问题所在获取方法(基于类的视图)
def get(request):
stalls = available_stalls()
products = Product.objects.all()
if 'cart' not in request.session:
request.session['cart'] = []
cart_count = 0
else:
cart_count = len(request.session['cart'])
context = {
"stalls": stalls,
"products": products,
'cart_count': cart_count
}
if request.user.is_authenticated:
user = request.user
customer = Customer.objects.filter(user=user)[0]
full_name = customer.full_name
context["name"] = full_name
return render(request, 'product_catalog.html', context)
post方法(基于类的视图)
def post(request):
if "product" not in request.POST or "quantity" not in request.POST:
raise Http404("Product or quantity not in POST data")
product_id = request.POST["product"]
quantity = request.POST["quantity"]
try:
product = Product.objects.get(id=product_id)
except:
raise Http404("Product ID not in database")
print(request.session["cart"])
request.session["cart"].append((product, quantity))
cart_count = len(request.session['cart'])
stalls = available_stalls()
products = Product.objects.all()
# TODO: Compute recommendations
return render(request, 'product_catalog.html', {
'added_to_cart': product,
'cart_count': cart_count,
'quantity': quantity,
'stalls': stalls,
'products': products
})
答案 0 :(得分:1)
when sessions are saved上的文档解释了这一点。基本上,会话仅在修改其中一个顶级键时自动保存。但是您要在会话中的现有列表中添加元素。您需要明确说出request.session.modified = True
来触发保存。