DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Django validate_unique method already exists message
Luis Solis
Luis Solis

Posted on

Django validate_unique method already exists message

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?

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: