Reputation: 1732
Is there a way of determining if an object exists in the database. If it does, an "object already exists" is returned. Otherwise, a new object is created.
Upvotes: 1
Views: 1432
Reputation: 1732
So, the solution I implemented had to go to the ModelForm
:
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('name',)
def clean(self):
if Label.objects.filter(name=self.cleaned_data['name'].lower()).exists()
raise forms.ValidationError('Label exists!')
return self.cleaned_data
Upvotes: 3
Reputation: 2539
How about using the get_or_create
method? With this, you will also see, whether or not the object has been newly created. If not, you return your "object already exists".
You should probably do this in your override of the post(request, *args, **kwargs)
method within your view.
See the docs for futher information
Upvotes: 0