Search code examples
pythondjangoweb-deployment

Python throwing variable scope error in Django app


I am currently working on a small Library management Django app, the following is one the view function

def issue_book(request):
    now = datetime.now()
    if now.month < 10:
        month = "0" + str(now.month)
    if now.day < 10:
        day = "0" + str(now.day)
    today = str(now.year) + "-" + month + "-" + day
    context = {
        'today': today
    }
    return render(request, 'admin_area/issue_book.html', context)

But this gives me an error as shown:

UnboundLocalError at /admin_area/issue_book
local variable 'day' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin_area/issue_book
Django Version: 3.2
Exception Type: UnboundLocalError

Exception Value:    local variable 'day' referenced before assignment

Can anyone explain the cause of the error!


Solution

  • The issue is that both day and month are not set i.e undefined when greater than 10:

    You could have:

    def issue_book(request):
        now = datetime.now()
        month = "0" + str(now.month) if now.month < 10 else str(now.month)       
        day = "0" + str(now.day) if now.day < 10 else str(now.day)        
        today = str(now.year) + "-" + month + "-" + day
        ...
    

    You can also have:

    def issue_book(request):
        now = datetime.now()
        today = now.strftime("%Y-%m-%d")
        context = {
            'today': today
        }
    ...
    

    For formatting strftime: https://www.programiz.com/python-programming/datetime/strftime