做网页的时候添加了增删改查的功能的时候跳错了

做网页的时候添加了增删改查的功能,在改的时候跳错了
错误信息是:
UnboundLocalError at /myadmin/building/update/1
local variable 'myfile' referenced before assignment
Request Method:    POST
Request URL:    http://127.0.0.1:8000/myadmin/building/update/1
Django Version:    4.1.5
Exception Type:    UnboundLocalError
Exception Value:    
local variable 'myfile' referenced before assignment
Exception Location:    C:\Users\user\Desktop\turingobject\myadmin\views\building.py, line 128, in update
Raised during:    myadmin.views.building.update
Python Executable:    C:\Users\user\PycharmProjects\pythonProject\venv\Scripts\python.exe
Python Version:    3.9.13
Python Path:    
['C:\\Users\\user\\Desktop\\turingobject',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\user\\PycharmProjects\\pythonProject\\venv',
 'C:\\Users\\user\\PycharmProjects\\pythonProject\\venv\\lib\\site-packages']
Server time:    Thu, 02 Feb 2023 11:46:55 +0800

具体代码如下:

def update(request,bid):
    '''执行信息编辑'''
    try:
        # 获取原图片名
        oldpicname = request.POST['oldpicname']
        # 判断是否有文件上传
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            cover_pic = oldpicname
        else:
            cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
            destination = open("./static/uploads/building/" + cover_pic, "wb+")
            for chunk in myfile.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
        #获取原图片

        ob = Building.objects.get(id=bid)
        ob.name = request.POST['name']
        ob.cover_pic = cover_pic
        ob.address = request.POST['address']
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info':"修改成功!"}
        # 判断删除老图片
        if myfile:
            os.remove("../static/uploads/building/" + oldpicname)
    except Exception as err:
        print(err)
        context = {'info': "修改失败!"}
        if myfile:
            os.remove("./static/uploads/product/" + cover_pic)

    return render(request,"myadmin/info.html",context)

目前不知道该怎么修改。

改了下:


def update(request,bid):
    '''执行信息编辑'''
    context = {'info': "修改失败!"}
    try:
        # 获取原图片名
        oldpicname = request.POST.get('oldpicname', '')
        # 判断是否有文件上传
        myfile = request.FILES.get("cover_pic", None)
        cover_pic = oldpicname
        if myfile:
            cover_pic = "{}.{}".format(str(time.time()), myfile.name.split('.').pop())
            destination_path = os.path.join("./static/uploads/building/", cover_pic)
            with open(destination_path, "wb+") as destination:
                for chunk in myfile.chunks():  # 分块写入文件
                    destination.write(chunk)

        #获取原图片
        ob = Building.objects.get(id=bid)
        ob.name = request.POST.get('name', '')
        ob.cover_pic = cover_pic
        ob.address = request.POST.get('address', '')
        ob.status = request.POST.get('status', '')
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "修改成功!"}

        # 删除老图片
        if myfile and oldpicname:
            old_pic_path = os.path.join("../static/uploads/building/", oldpicname)
            if os.path.exists(old_pic_path):
                os.remove(old_pic_path)

    except Exception as err:
        print(err)

    return render(request,"myadmin/info.html", context)

myfile是否在update之外有定义过,看提示是因为你在update函数内部引用和更改全局变量myfile导致的,

 myfile = request.FILES.get("cover_pic", None)

前面加上:

nonlocal myfile 

或者:

global myfile

试下