How to detect update in django admin form validation module

I have a custom validator for a field in a model Postthat will be used in the admin interface authentication goal is to verify that no other e-mail does not have the same url, and category, but I can not find a way to distinguish from the renovation or newPost ; which in the case of an update will not be a problem with the existence of Postthe same URL and category.

Here is the validator:

class MyPostAdminForm(forms.ModelForm):

    class Meta:
        model = Post

    def clean_url(self):
        url = self.cleaned_data['url']        
         # if doesn't have any category then 
         # just return the url to handle the error.
        try:
            cat = self.cleaned_data['category']
        except KeyError:
            return url

        if UPDATE: #  UPDATE???
            #DON'T  COMPLAIN IF IS THE SAME, RETURN THE URL
            return url
        else: # IS NEW!
            try:
                Post.objects.get(category=cat, url=url)
            except Post.DoesNotExist:
                return url
            else:
                raise forms.ValidationError('Already exists post with category "%s" and url "%s"'%(cat, url))

Any ideas?

+3
source share
1 answer

: unique_together , , .

, , , , - , self.instance pk.

if hasattr(self, 'instance') and self.instance.pk is not None:
    #update
else:
    #new
+4

Source: https://habr.com/ru/post/1778946/


All Articles