On Jun 10, 9:42 pm, Adi <[EMAIL PROTECTED]> wrote: > The application flow works like this: You create a Relation object > within the context of an Owner Object. There is a rule that says that > a owner cannot have two Relation with the same pet value. How can I > create a validation on the form that can check this rule. Basically, > How can i pass owner object that I have in the view when I call > RelationForm.is_valid()
A trick I use quite frequently with ModelForms is to require that an instance is passed to the form on creation:: class RelationForm(ModelForm): class Meta: model = Relation fields = ('pet') class NoInstance(Exception): """Raise this error when an instance was not passed to the form. """ pass def __init__(self, *args, **kwargs): super(RelationForm, self).__init__(*args, **kwargs) # this isn't necessary, but helps remind you that this # form will expect self.instance.user to exist if not self.instance or not self.instance.owner: raise self.NoInstance("You must pass an"\ " instance to this form.") def clean(self): try: Relation.objects.get( owner=self.instance.owner, pet=self.cleaned_data.get('pet')) except Relation.DoesNotExist: return self.cleaned_data raise forms.ValidationError( 'You cannot have two of the same pet') Then in your view, you have to do one of the following:: def my_view(request): # for a new Relation model: instance = Relation(user=request.user) # or for an existing Relation model: instance = Relation.objects.get(user=request.user) if request.method == 'POST': form = RelationForm(request.POST, instance=instance) if form.is_valid(): ... else: form = RelationForm(instance=instance) return render_to_response(...) Hope that's helpful. - whiteinge --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com 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 -~----------~----~----~----~------~----~------~--~---