How to auto-select and hide a foreign key form field if there is only 1 choice in the queryset.

Assuming models looking like this:

class Team(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE)

class Task(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

If I have a TaskForm:

class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ["name", "team"]

Is there a way to auto-select and hide the team field if there is only a single object in the team queryset of the form?

You can do that on the __init__ method.

I believe you can define a field’s initial and disable it.

1 Like