Django fill selection box based on model request

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 run a form using only foreignkeys on host_end, it always displays all the 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 need zones corresponding to this domain .. not all domains.

+3
source share
1 answer

The source data in the selection or foreign key field is used to determine what is selected in this field, and not the available available parameters. If you want to define a list of options, you need to override the method __init__and make 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)
+2
source

Source: https://habr.com/ru/post/1742840/


All Articles