djangodjango-admindjango-admin-filtersdjango-admin-toolsdjango-admin-actions

Django how to create errors while adding new objects


See first the code.

models.py

class Schauspieler(models.Model):
    schauspieler = models.CharField(max_length=100)

    def __str__(self):
        return self.schauspieler

admin.py

class SchauspielerAdmin(admin.ModelAdmin):
    ordering = ('schauspieler',)

admin.site.register(Schauspieler, SchauspielerAdmin)

localhost schauspieler tables

You can see i have there 2 time the name Alexander Ludwig. This is a list of actors in the admin. Because the names of the actors are too much, I do not remember which ones i have created and which ones not. If the name exists than should come a error while adding. How can i do this?


Solution

  • You should make the schauspieler unique, with unique=True [Django-doc]:

    class Schauspieler(models.Model):
        schauspieler = models.CharField(max_length=100, unique=True)
    
        def __str__(self):
            return self.schauspieler

    You probably however will first need to remove the already existing duplicates, since otherwise the database will reject the migration, because at that moment in time there are already duplicates.