Home > OS >  MultiValueDictKeyError at /change-part/. In python django
MultiValueDictKeyError at /change-part/. In python django

Time:10-11

So i try to make a upload image system, and i make two different type of image, there are static and dynamic

and i try to make a different act/function for thoose type, so i made a two if

one like this,

if len(request.FILES['img_dinamic']) != 0:
    part = WebPart.objects.get(part=partToChange)
    if len(part.dinamic_image) > 0:
        os.remove(part.dinamic_image.path)
    img_dinamic = request.FILES['img_dinamic']
else:
    img_dinamic = ""

and the other one is like this

if len(request.FILES['img_static']) != 0:
    img_static = request.FILES['img_static']
else:
    img_static = ""

and when i try to run the system, it appears some error like this

MultiValueDictKeyError at /change-part/
'img_static'

any body can help me ?

CodePudding user response:

request.FILES is a dictionary like object(Subclass of dict). So when you try to access a key and if the key does not exist within the dictionary, dictionary[key] always raise KeyError. The solution is to use the get method instead.

img_static = request.FILES.get('img_static', "")

This will try to access the key img_static from request.FILES. If it does not exist default value(second argument) will be used.

  • Related