Элементы не добавляются в корзину анонимных пользователей?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Элементы не добавляются в корзину анонимных пользователей?

Сообщение Anonymous »

Я хочу сделать не введенный в систему пользователей, которые могут добавить элементы в свою корзину
, но когда я нажимаю «Добавить в корзину без элемента».

Код: Выделить всё

from django.shortcuts import render
from django.http import JsonResponse
import json
import datetime
from .models import *

def store(request):

if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
#Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']

products = Product.objects.all()
context = {'products':products, 'cartItems':cartItems}
return render(request, 'store/store.html', context)

def cart(request):

if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
#Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']

context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)

def checkout(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
#Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']

context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/checkout.html', context)

def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', productId)

customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)

orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)

orderItem.save()

if orderItem.quantity 
это my cart.js: < /p>
var UpdateBtns= document.getElementsByClassName('update-cart')
for(i=0;i<  UpdateBtns.length;i++){
UpdateBtns[i].addEventListener('click',function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId',productId,'action',action)

console.log('USER:',user)
updateUserOrder(productId,action)
})
}

function updateUserOrder(productId,action){
var url = '/update_item/'
fetch(url,{
method : 'POST',
headers : {
'content-Type':'application/json',
'X-CSRFToken':csrftoken,

},
body:JSON.stringify({'productId':productId,'action':action})

})
.then((Response)=>{
return Response.json()
})
.then((data) =>{
console.log('data:',data)
})
}
< /code>
Это моя страница заказа.html: < /p>
{% extends 'shop_templates/main.html' %}
{% load static%}
{%block content %}




{% csrf_token %}

{% if not request.user.is_authenticated %}





{% endif %}



shipping information :


















Paypal info
payment




[url={% url ]← Go Back[/url]

Order Summary

{% for item in items %}


[img]{{item.product.imageURL}}[/img]
{{item.product.product_name}}
{{item.product.price}}
{{item.quantity}}

{% endfor %}
Items : {{order.get_cart_items}}
Cost : {{order.get_cart_total|floatformat:2}}




var csrftoken = '{{csrf_token}}'
var shipping = '{{order.shipping}}'
var total = '{{order.get_cart_total}}'
var user = '{{request.user}}'

if (shipping == false){
document.getElementById('shipping-info').classList.add("hidden");
}
if(user !='AnonymousUser'){
document.getElementById('user-info').classList.add("hidden");
}

if(shipping ==false && user !='AnonymousUser'){
document.getElementById('form-wrapper').classList.add("hidden");
document.getElementById('payment-info').classList.remove("hidden");
}
var form = document.getElementById('form')
csrftoken = form.getElementsByTagName('input')[0].value
form.addEventListener('submit',function(e){
e.preventDefault()
console.log('form Submitted')
document.getElementById('form-button').classList.add("hidden")
document.getElementById('payment-info').classList.remove("hidden")
})
document.getElementById('payment').addEventListener('click',function(e){
submitFormData()

})
function submitFormData(){
console.log('payment process...')
var userFormData ={
'name':null,
'email':null,
'total':total,
}
var shippingInfo =  {
'address':null,
'city':null,
'state':null,
'zipcode':null,
}
if(shipping != false){
shippingInfo.address = form.elements.address.value
shippingInfo.city = form.elements.city.value
shippingInfo.state = form.elements.state.value
shippingInfo.zipcode = form.elements.zipcode.value
}
if(user =='AnonymousUser'){
userFormData.name = form.elements.name.value
userFormData.email = form.elements.email.value
}

console.log('shippingInfo:',shippingInfo)
console.log('User info:',userFormData)

var url = '/order_process'
fetch(url,{
method : 'POST',
headers : {
'Content-Type' : 'application/json',
'X-CSRFToken' : csrftoken,
},
body:JSON.stringify({'form':userFormData,'shipping':shippingInfo})
})
.then((response) => response.json())
.then((data) => {
console.log('sucess',data);
alert('Transation Completed');
window.location.href= "{% url 'Store' %}"
})
}

{% endblock content %}
У меня есть проблема для анонимных пользователей, когда анонимный пользователь нажимает на добавление элементов тележки, не добавляясь в корзину

Подробнее здесь: https://stackoverflow.com/questions/797 ... users-cart
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Элементы не добавляются в корзину анонимных пользователей?
    Anonymous » » в форуме Python
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Элементы не добавляются в корзину анонимных пользователей?
    Anonymous » » в форуме Python
    0 Ответы
    2 Просмотры
    Последнее сообщение Anonymous
  • Элементы не добавляются в корзину анонимных пользователей?
    Anonymous » » в форуме Python
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Элементы не обновляются и не добавляются в корзину
    Anonymous » » в форуме C#
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • Как сделать маршрут /login доступным только для анонимных пользователей в Symfony 4?
    Anonymous » » в форуме Php
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»