开发者

Django populate select field based on model query

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=开发者_JS百科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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜