Using get_or_create in a view
I am importing users from LDAP into MySQL and I want to get/create profiles as such:
profile_obj, created_profile = UserProfile.objects.get_or_create(user=user_obj)
Django's throwing me an exception, which seems completely ironic considering the function I am using.
UserProfile matching query does not exist.
Am I using it incorrectly?
/Users/bdunlay/python/python-2.5/lib/python2.5/site-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/django/internal/accounts/views.py in ad_search
status = update_user(keyword, update_photos)
...
▶ Local vars
/django/internal/accounts/views.py in update_user
profile_obj, created_profile = UserProfile.objects.get_or_create(user=user_obj)
...
▶ Local vars
/Users/bdunlay/python/python-2.5/lib/python2.5/site-packages/django/db/models/manager.py in get_or_create
return self.get_query_set().get_or_create(**kwargs) ...
▶ Local vars
/Users/bdunlay/python/python-2.5/lib/python2.5/site-packages/django/db/models/query.py in get_or_create
obj.save(force_insert=True, using=self.db) ...
▶ Local vars
/django/internal/../internal/accounts/models.py in save
this = UserProfile.objects.get(id=self.id)
...
▶ Local vars
/Users/bdunlay/python/python-2.5/lib/python2.5/site-packages/django/db/models/manager.py in get
return self.get_query_set().get(*args, **kwargs) ...
▶ Local vars
/Users/bdunlay/python/python-2.5/lib/python2.5/site-packages/django/db/models/query.py in get
% self.model._meta.object_name) ...
▶ Local vars
Edit:
As per a request below, the save function.
def save(self, force_insert=False, force_update=False, using=settings.DATABASES['default']):
super(UserProfile, self).save() # I just added this line and it seems to work now.
this = UserProfile.objects.get(id=self.id)
try:
if this.photo != self.photo:
this.photo.delete()
except:
pass
# if this lives in a unresolved path, something is wrong. scrap it.
try:
if self.photo:
statinfo_photo = os.stat(self.photo.path)
except:
self.photo = None
try:
if self.thumbnail:
statinfo_thumbnail = os.stat(self.thumbnail.path)
except:
self.thumbnail = None
#get mtime stats from file
thumb_update = False
if self.thumbnail:
statinfo1 = os.stat(self.photo.path)
statinfo2 = os.stat(self.thumbnail.path)
if statinfo1 > statinfo2:
thumb_update = True
if self.photo and not self.thumbnail or thumb_update:
# from PIL import Image
try:
if self.thumbnail:
self.thumbnail.delete()
except:
pass
THUMB_SIZE = (50, 50)
#self.thumbnail = self.photo
image = Image.open(self.photo.path)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
(head, tail) = os.path.split(self.photo.path)
(a, b) = os.path.split(self.photo.name)
if not os.path.isdir(head + '/thumbs'):
os.mkdir(head + '/thumbs')
image.save(head + '/thumbs/' + tail)开发者_运维知识库
self.thumbnail = a + '/thumbs/' + b
super(UserProfile, self).save()
精彩评论