Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - 'NoneType' object has no attribute 'id' in Django

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...