On Thu, 2009-04-30 at 23:46 -0300, Gabriel wrote:
> I have a model with a custom field:
[...]
> class AutoSlugField(fields.SlugField):
> def __init__(self, prepopulate_from, force_update = False, *args,
> **kwargs):
> self.prepopulate_from = prepopulate_from
> self.force_update = force_update
> super(AutoSlugField, self).__init__(*args, **kwargs)
>
> def pre_save(self, model_instance, add):
> if self.prepopulate_from:
> return slugify(model_instance, self, getattr(model_instance,
> self.prepopulate_from), self.force_update)
> else:
> return super(AutoSlugField, self).pre_save(model_instance, add)
[...]
> when I call form.save() it returns a Project instance without the slug
> value, although the field is correctly saved into the database.
>
> Any idea why this is happening ?
The Model class calls pre_save() to work out the value to save into the
database. That's working correctly for you, as you've noticed: the right
value is being saved.
Some Field subclasses in Django also use pre_save() as a way to
normalise the value in the Model attribute. It sounds like you want that
to happen -- you would be normalising it from "nothing at all" to the
correct value. In that case, you need to call setattr() to set the
attribute value. That's why model_instance is passed as a parameter to
pre_save(). You could write something like this:
def pre_save(self, model_instance, add):
if self.prepopulate_from:
value = slugify(model_instance, self,
getattr(model_instance, self.prepopulate_from),
self.force_update)
else:
value = super(AutoSlugField,
self).pre_save(model_instance,
add)
setattr(model_instance, self.attname, value)
return value
Does that clear things up?
Regards,
Malcolm
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---