pythondjangoobjectormnot-exists

Display 1 when no data is exist in database


I am trying to generate incremental id whenever I am adding new data in my model. here I am getting the the next number whenever I am adding new data. but If there is no any data in my table its giving me error. 'NoneType' object has no attribute 'tax_id'

Here is my code

views.py

def tax_settings(request):
latest_id = (Tax_Settings.objects.last()).tax_id+1
if request.method == 'POST':
    tax_id = latest_id
    name = request.POST['tax_name']
    tax_percentage = request.POST['tax_percentage']
    tax_details=Tax_Settings.objects.create(tax_id=tax_id, name=name, tax_percentage=tax_percentage)
    tax_details.save()
    next_id = (Tax_Settings.objects.last()).tax_id+1
    return render(request,"settings/tax-settings.html",{"latest_id":next_id})
else:
    return render(request,"settings/tax-settings.html",{"latest_id":latest_id})

html

<input type="text" class="form-control" placeholder="{{latest_id}}" name="tax_id"  disabled>

which condition I can give to my latest_id if data(tax_id) not exists?


Solution

  • You are trying to do too much in too few lines of code. Wherever you use queryset .last() or .first() you must explicitly handle the case where it returns None!

    You need code of the form:

    o = Tax_Settings.objects.last()
    if o is not None:
        tax_id = o.tax_id + 1
    else:
        tax_id = 1 # if that's a sensible default value
    

    or even

    o = Tax_Settings.objects.last()
    assert o is not None, "This can't happen!" # except obviously, it does in this question.