Python 动态填充django自定义用户注册表中字段的dropdownlist时出现问题

Python 动态填充django自定义用户注册表中字段的dropdownlist时出现问题,python,ajax,django,Python,Ajax,Django,我在Django中创建了一个自定义用户注册表,如下所示: class RegistrationForm(UserCreationForm): state = forms.ModelChoiceField(State.objects.all()) booth = forms.ModelChoiceField(Booth.objects.none()) first_name = forms.RegexField(regex=r'^\w+$', widget=forms

我在Django中创建了一个自定义用户注册表,如下所示:

class RegistrationForm(UserCreationForm):

     state = forms.ModelChoiceField(State.objects.all())
     booth = forms.ModelChoiceField(Booth.objects.none())
     first_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("First name"), error_messages={ 'invalid': _("This value must contain only letters") })
     last_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Last name"), error_messages={ 'invalid': _("This value must contain only letters") })
     password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
     password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
     date_of_birth = forms.DateField(widget=forms.TextInput(attrs= {'class':'datepicker'}))
     sex = forms.ChoiceField(choices=(('M', 'MALE'), ('F', 'FEMALE')), label=_("Sex"))
     voter_id = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Voter Id"))
     is_election_staff = forms.BooleanField(initial=False, required=False)

class Meta:
    model = CustomUser
    fields = ['state', 'booth', 'first_name', 'last_name', 'voter_id', 'date_of_birth', 'sex', 'is_election_staff']
    $(document).ready(function() {
            $('.datepicker').datepicker();
             $('#id_state').on('change', function() {
                alert(this.value );
                $.ajax({
                    url: '/voting/api/booths/',
                    dataType: 'json',
                    type: 'GET',
                    data: {state_id : $('#id_state').val()},
                    success: function(data) {
                        $('#id_booth').empty();
                        for (row in data) {
                            $('#id_booth').append($('<option></option>').attr('value', data[row].id).text(data[row].name));
                        }
                    }
                });
            });

        });
然后在register.html中,我根据booth选择的状态填充了dropdownlist,如下所示:

class RegistrationForm(UserCreationForm):

     state = forms.ModelChoiceField(State.objects.all())
     booth = forms.ModelChoiceField(Booth.objects.none())
     first_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("First name"), error_messages={ 'invalid': _("This value must contain only letters") })
     last_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Last name"), error_messages={ 'invalid': _("This value must contain only letters") })
     password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
     password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
     date_of_birth = forms.DateField(widget=forms.TextInput(attrs= {'class':'datepicker'}))
     sex = forms.ChoiceField(choices=(('M', 'MALE'), ('F', 'FEMALE')), label=_("Sex"))
     voter_id = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Voter Id"))
     is_election_staff = forms.BooleanField(initial=False, required=False)

class Meta:
    model = CustomUser
    fields = ['state', 'booth', 'first_name', 'last_name', 'voter_id', 'date_of_birth', 'sex', 'is_election_staff']
    $(document).ready(function() {
            $('.datepicker').datepicker();
             $('#id_state').on('change', function() {
                alert(this.value );
                $.ajax({
                    url: '/voting/api/booths/',
                    dataType: 'json',
                    type: 'GET',
                    data: {state_id : $('#id_state').val()},
                    success: function(data) {
                        $('#id_booth').empty();
                        for (row in data) {
                            $('#id_booth').append($('<option></option>').attr('value', data[row].id).text(data[row].name));
                        }
                    }
                });
            });

        });

在上面的视图函数中,我检查了form.is_valid(),它返回false。任何人都可以告诉我我犯了什么错误。

布斯值应该在queryset中,然后传递到字段-
Booth.objects.none()
-现在它总是空的

您可以动态更改此查询集,如下所示:

class RegistrationForm(UserCreationForm):

    # your fields here 

    def __init__(self, *args, **kwargs):
      super(RegistrationForm, self).__init__(*args, **kwargs)

      # check state in POST data and change qs 
      if 'state' in self.data:  
          self.fields['booth'].queryset = Booth.objects.filter(state_id=self.data.get('state'))

Booth值应该在queryset中,传递给字段-
Booth.objects.none()
-现在它总是空的

您可以动态更改此查询集,如下所示:

class RegistrationForm(UserCreationForm):

    # your fields here 

    def __init__(self, *args, **kwargs):
      super(RegistrationForm, self).__init__(*args, **kwargs)

      # check state in POST data and change qs 
      if 'state' in self.data:  
          self.fields['booth'].queryset = Booth.objects.filter(state_id=self.data.get('state'))

state
booth
字段是否应该接受多个参数?是的,这两个字段都是dropdownlistpost完整的回溯。没有这样的回溯,我在问题中发布的是我提交表单后在UI中收到的唯一错误消息。为了更清晰,我发布了相应的视图,其中我通过表单检查表单是否有效。is_valid()返回False。is
state
booth
字段应接受多个参数?是的,两者都是dropdownlistpost完整的回溯。没有此类回溯,我在问题中发布的是我在提交表单后在UI中收到的唯一错误消息。为了更清晰,我发布了相应的视图,其中通过返回False的form.is_valid()检查表单是否有效。