- July 17, 2007
- newforms models fields forms save
- 0 (after 0 ratings)
I wanted to make the objects of a particular model approvable and store the timestamp of when that happened. In other frameworks/languages, I used to combined those in one "approved_at" field, which would be NULL if an object was currently unapproved.
I tried different approaches to implement this in django, and this is the best I came up with so far. Basically, the code in setattr makes sure that the field, once set, will not be updated again.
Overriding setattr__() could also be a solution to determining if a field value has changed in save(), a question that seems come up from time to time in #django.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class ApprovedStateField(forms.fields.Field): widget = forms.CheckboxInput def clean(self, value): super(ApprovedStateField, self).clean(value) if bool(value): return datetime.datetime.now() else: return None class Keyword(models.Model): name = models.CharField(maxlength=30) approved_at = ApprovedStateField() def __setattr__(self, name, value): # don't change the approved_at attribute if it is already set if (name <> "approved_at") or (not hasattr(self, 'approved_at')) or (self.approved_at is None): super(Keyword, self).__setattr__(name, value)