Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django populate select field based on model query

Tags:

django

I have the following model

class DNS(models.Model):
    domain = models.ForeignKey(Domain)
    host_start = models.CharField(max_length=150, blank=True, null=True)
    type = models.SmallIntegerField(max_length=1, default=0, choices=DNS_CHOICE)
    value = models.SmallIntegerField(max_length=3, default=0, blank=True, null=True)
    ip = models.IPAddressField(blank=True, null=True)
    host_end = models.ForeignKey("DNS", blank=True, null=True)
    other_end = HostnameField(max_length=150, blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    sticky = models.BooleanField(default=0)
    other = models.BooleanField(default=0)

When I try to init a form with just foreignkeys on host_end.. it always shows all entries in the DNS table

domain = Domain.objects.get(id=request.GET['domain'], user=request.user, active=1)
form = DNSFormCNAME(initial={'ip': settings.MAIN_IP, 'type': request.GET['type'], 'host_end': DNS.objects.filter(domain=domain)})

I just want the zones that match that domain.. not all domains.

like image 297
Mike Avatar asked Dec 21 '25 07:12

Mike


1 Answers

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)
like image 55
Daniel Roseman Avatar answered Dec 24 '25 01:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!