[Django]-Django populate select field based on model query

3👍

Initial data to a choice or foreign key field is used to determine what is selected in that field, not what the available options are. If you want to determine the list of options, you need to override the form’s __init__ method and do it there.

class DNSFormCNAME(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.domain = kwargs.pop('domain', None)
        super(DNSFormCNAME, self).__init__(*args, **kwargs)
        if self.domain:
            self.fields['host_end'].queryset = DNS.objects.filter(domain=domain)

Leave a comment