Search code examples
pythondjangomodel

Control the Error from Meta class in Django model


I'm working with Blog website with Django, I have a model called Post and its like this:

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    txt = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self) -> str:
        return f"{self.user} {self.title}"
    
    class Meta:
        ordering = ['-created_at']
        unique_together = ['title', 'txt']

and so when a user try to create more than one Post with the same title and text it must launch an Error, but I don't know how to control this error and turn it into a proper Error and code will launch the Constraint_failed error and I wanna control this kind of Errors not just in the Admin panel but in the User client side that User can see his mistakes and fix it.


Solution

  • You can fix this problem by validating the user input data. To do this, you can create a Django model form or use a regular Django form, depending on your choice.

    forms.py

    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = ['title', 'txt']
    
        def clean(self):
            cleaned_data = super().clean()
            title = cleaned_data.get('title')
            txt = cleaned_data.get('txt')
    
            if title and txt:
                existing_post = Post.objects.filter(title=title, txt=txt).exists()
                if existing_post:
                    raise forms.ValidationError("A post with the same title and text already exists.")
    
            return cleaned_data