I'm from a PHP background but have been given a Django project to administer, I've brought it over to a new server running Django 1.2.5 (Python2.6) and got it all running as it was on the old one. I have now been tasked with fixing bugs from the old developers. So far so good, but I've hit a stumbling block with an ImageField. Essentially a user can have an image logo uploaded (this works). However when a user without a logo edits their details Django throws an error:
ValueError: The 'org_logo' attribute has no file associated with it.
The code snippet that results in the error is:
user = request.user
org 开发者_如何学JAVA= user.organisation
if not checkLogoFile(org):
org.org_logo = ''
org.save()
The function checkLogoFile looks like this:
def checkLogoFile(org):
from os.path import exists
path = org.org_logo.path
if path:
file_name = path.split('/')[-1]
return exists(settings.MEDIA_ROOT+'logo/'+file_name)
return False
The way I understand it the if checkLogoFile returns false then the org_logo value will be a zero length string. If the org_logo contains a path then that is returned. As mentioned this fails when an image logo is not present but works when one is. :-/
Any pointers would be very helpful as I've scoured Google and so far am not getting anywhere.
Fixing the problem:
def checkLogoFile(org):
from os.path import exists
path = org.org_logo.path if org.org_logo else None
if path:
file_name = path.split('/')[-1]
return exists(settings.MEDIA_ROOT+'logo/'+file_name)
return False
But anyway, I don't really get why complicate this checking this way. Why not just
def checkLogoFile(org):
from os.path import exists
path = org.org_logo.path if org.org_logo else None
return path and exists(path)
精彩评论