Python 在 Django 应用程序中抛出变量范围错误

Python throwing variable scope error in Django app

我目前正在开发一个小型图书馆管理 Django 应用程序,以下是其中一个视图功能

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)

但这给了我一个错误,如图所示:

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

谁能解释一下错误的原因!

我猜你想 return 01,02,...10,11,12 等?

试试这个:

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

我宁愿使用 strftime 而不是执行上述操作:

def issue_book(request):
    today = datetime.now().strftime('%Y-%m-%d')
    context = {
        'today': today
    }
    return render(request, 'admin_area/issue_book.html', context)

问题是 daymonth 都没有设置,即大于 10 时未定义:

你可以:

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
    ...

您还可以拥有:

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

格式化 strftime: https://www.programiz.com/python-programming/datetime/strftime