Django model booleanfield only 1 True for table -
i have model
class owner(models.model): name = models.charfield(max_length=10) class phonenumber(models.model): isactive = model.booleanfield(default=false) owner = model.foreignkey('owner')
i want enforce 1 phonenumber active if user, when creating or editing 'not active' phonenumber, accidentally sets 'active' , there 'active' phonenumber form should not submit , clear error displayed change 'active' field false , error text "please deactivate old active phonenumber before assigning new active phonenumber"
how do this? in validation method in class check ?
thank you
often validation can done automatically defining unique_together
in model's meta class, here not work possibly have many inactive phone numbers each user. need custom validation. 1 way in clean
method of model itself, called when form validated.
def clean(self): if self.isactive: active = phonenumber.objects.filter(isactive=true, owner=self.owner) if self.pk: active = active.exclude(pk=self.pk) if active.exists(): raise validationerror("an active phone number exists user")
Comments
Post a Comment