loading...
Cover image for Django validate_unique method already exists message

Django validate_unique method already exists message

agenteand profile image Luis Solis ・1 min read

As always to write in stack overflow it's something beginners developers like me can't do

I made this post and get answers from people who have not read the question well.

the question is this: How to show admin users which is the instance that already exists so they can edit it if they want?

it is not a good practice to overwrite the method validate_unique and I don't know if it would be correct to validate unique fields in the clean() method.

but imagine💡 the following situation: you want to show admin users which is the instance that already exists so they can edit it if they want, I think it would be more intuitive when working with thousands of data.

This's what I've done:

the following code is just an example - think about it as a pseudocode although I tried it and it works, I know it could be better

 def clean(self):
        lockup ={}

        unique_togethers = self._meta.unique_together[0]#these could throw an error

        for field in unique_togethers:
            f = self._meta.get_field(field)

            value = getattr(self, f.attname)

            if value is None:
                 continue

            if f.primary_key and not self._state.adding:
                    continue

            lockup[str(field)] = value

        qs = snippet.objects.filter(**lockup)

        if qs.exists and self._state.adding:
            raise ValidationError(
                     format_html('''this object already exist plese edit it on <a href="{}">Edit</a>''', 
                                  reverse('admin:testing_snippet_change', args=(qs[0].pk,))))

Results:

Alt Text
Is this approach correct, how to apply it to the validation_unique method to works in all unique validations?

Posted on by:

Discussion

pic
Editor guide