I get the 'NoneType' object has no attribute 'id' error when opening a URL which view is this one:
@login_required
def order_checkout_view(request):
product_id = request.session.get("product_id") or None
if product_id == None:
return redirect("/")
product = None
try:
product = Product.objects.get(id=product_id)
except:
return redirect("/")
user = request.user
order_id = request.session.get("order_id")
order_obj = None
new_creation = False
try:
order_obj = Order.objects.get(id=order_id)
except:
order_id = None
if order_id == None:
new_creation = True
order_obj = Order.objects.create(product=product, user=user)
if order_obj != None and new_creation == False:
if order_obj.product.id != product.id:
order_obj = Order.objects.create(product=product, user=user)
request.session['order_id'] = order_obj.id
form = OrderForm(request.POST or None, product=product, instance=order_obj)
if form.is_valid():
order_obj.shipping_address = form.cleaned_data.get("shipping_address")
order_obj.billing_address = form.cleaned_data.get("billing_address")
order_obj.mark_paid(save=False)
order_obj.save()
del request.session['order_id']
return redirect("/success")
return render(request, 'orders/checkout.html', {"form": form, "object": order_obj})
The exception location is in this line
if order_obj.product.id != product.id:
There's an existing product in the database, however does this mean in this case the Product is 'None'? What could be the problem here?
question from:
https://stackoverflow.com/questions/65713121/nonetype-object-has-no-attribute-id-in-django 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…