0

I have a Team model and Staff model (foreign to Team). Each Team Object can related to 1 - 10 Staff objects.

Each staff object have a boolean field to indicate if he/she is team coordinator.

How can I, in django admin page, ensure when admin users are entering team information as well as related staff information (inline), he/she must choose at least one team coordinator (can all staff within a team are all coordinator but cannot zero of them are).

Thanks for suggestion.

models.py

class Team(models.Model):
team_id = models.AutoField(primary_key=True, verbose_name='Team ID')
team_name = models.CharField(max_length=100, verbose_name='Team Name')
def __str__(self):
    return self.team_name
class Meta:
    verbose_name='Team'

class Staff(models.Model):
    staff_id = models.AutoField(primary_key=True)
    team_id = models.ForeignKey(Team)
    staff_name = models.CharField(max_length=100, verbose_name='Staff Name')
    is_team_coord = models.BooleanField(verbose_name='Is Team Coordinator', default=False)
    def __str__(self):
        return self.staff_name
    class Meta:
        verbose_name='Staff'

admin.py

class StaffInLine(admin.TabularInline):
model = Staff
def get_max_num(self, request, obj=None, **kwargs):
    return 10
def get_min_num(self, request, obj=None, **kwargs):
    return 1

class TeamAdmin(admin.ModelAdmin):
    inlines = [StaffInLine]
Pang
  • 512
  • 3
  • 11
  • 31

1 Answers1

0

I have found the answer myself by referencing this link Inline Form Validation in Django

The complete solution is:

forms.py

class StaffInLineFormSet(forms.models.BaseInlineFormSet):
    def clean(self):
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data.get('is_team_coord') is True:
                    count += 1
            except AttributeError:
                pass
        if count == 0:
            raise forms.ValidationError('You must choose at least one Team Coordinator')

admin.py

class StaffInLine(admin.TabularInline):
    model = Staff
    formset = StaffInlineFormSet
    def get_max_num(self, request, obj=None, **kwargs):
        return 10
    def get_min_num(self, request, obj=None, **kwargs):
        return 1
Community
  • 1
  • 1
Pang
  • 512
  • 3
  • 11
  • 31