Hi,
I have a form where I validate in the clean method whether a ProjectMembership object already exist, that has the same values for project and member. This is due that I have in the ProjectMembership model defined a unique_together constraint for project and member. This works fine actually.
class ProjectMembershipForm(forms.ModelForm):
project = forms.ModelChoiceField(Project.objects, widget=HiddenInput())
class Meta:
model = ProjectMembership
def clean(self):
cleaned_data = self.cleaned_data
project = cleaned_data.get("project")
member = cleaned_data.get("member")
print ProjectMembership.objects.filter(project=project, member=member).count()
if ProjectMembership.objects.filter(project=project, member=member).count() > 0:
del cleaned_data["project"]
del cleaned_data["member"]
raise forms.ValidationError('The user "%s" is already part of the project team for project "%s".' % (member, project))
return cleaned_data
But now I'm asking myself how I can judge in the clean method whether the user tries to create a new relationship or update a relationship. Because with this clean method it is not possible to do an update, since it returns the error message that the entry already exist.