Filter a Django form select element based on a previously selected element

前端 未结 2 1734
栀梦
栀梦 2021-02-03 11:28

Let\'s consider the following models

models.py

Class Brand(models.Model):
    company_name = models.CharField(max_length=100)


class CarModel(models.Model         


        
2条回答
  •  囚心锁ツ
    2021-02-03 11:55

    class Country(models.Model):
       country_name=models.CharField(max_length=10, blank=True, null=True)
    
    class State(models.Model):
       state_name=models.CharField(max_length=10, blank=True, null=True)
    
    class MyCustomModal(models.Model):
       country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True)
       state = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True)
    

    Here is my Form

    class MyCustomForm(forms.ModelForm):
        class Meta:
            model = MyCustomModal
            fields = [
                'country',
                'state',           
            ]        
    
        def __init__(self, *args, **kwargs):
            super(MyCustomForm, self).__init__(*args, **kwargs)        
            self.fields['country'] = forms.ChoiceField(choices=[('1','india'),('2','US')])
            self.fields['state'].queryset = State.objects.filter(pk=2)
    

提交回复
热议问题