Learner
Learner

Reputation: 349

Making field unique in Django Admin

I have a model

class ScrapEventInstructionMap(models.Model):
    instruction = models.ForeignKey(Instruction)
    scrap_code = models.CharField(max_length=100, null=True, blank=True)
    event_code = models.CharField(max_length=100, null=True, blank=True)

    class Meta:
        unique_together = (("instruction", "event_code"), ("instruction", "scrap_code"))

I have used unique_together so that for a particular instruction, scrap_code and event_code should be unique. And from frontend if we're clicking on a particular scrap_code and event_code the instruction page is opening.

I am using InlineModelAdmin in Admin.py so that for one instruction there can be multiple scrap_code or event_code

But issue is like we have two instructions, Instruction 1 and Instruction 2 So if I am entering same scrap_code or event_code in both instructions. It is saving. I have to restrict it in admin page that event_code and scrap_code should also be unique for different instructions.

Upvotes: 1

Views: 553

Answers (2)

ar7n
ar7n

Reputation: 201

You should add custom validation in BaseInlineFormSet of InlineAdmin. Here is example of BaseInlineFormSet validation.

Upvotes: 1

Gorkhali Khadka
Gorkhali Khadka

Reputation: 835

Try this

class ScrapEventInstructionMap(models.Model):
    instruction = models.ForeignKey(Instruction)
    scrap_code = models.CharField(max_length=100, null=True, blank=True)
    event_code = models.CharField(max_length=100, null=True, blank=True)

    class Meta:
        unique_together = (("event_code", "scrap_code"))

Upvotes: 1

Related Questions