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

2024-09-25 02:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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']

然后在注册.html我正在根据她选择的州填充booth的dropdownlist,如下所示:

    $(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));
                        }
                    }
                });
            });

        });

但问题是,在提交表单时,我在UI中收到以下错误消息:

选择一个有效的选项。该选项不是可用选项之一

谁能告诉我我在这里犯了什么错误吗。你知道吗

编辑:在我的视图.py办理登记表提交:

  @csrf_protect
  def register(request):
   if request.method == 'POST':
    form = RegistrationForm(request.POST)
    pdb.set_trace()
    if form.is_valid():
        print "In register request = "+ str(request.POST)
        form.save()
        return HttpResponseRedirect('/voting/register/success/')
     else:
       form = RegistrationForm()
     variables = RequestContext(request, {
      'form': form
     })
return render_to_response(
'registration/register.html',
variables,
)

在上面的视图中我已经检查了函数表格.u有效吗()返回false。请任何人告诉我我犯了什么错误。你知道吗


Tags: nameformidtruevaluerequestrequiredforms
1条回答
网友
1楼 · 发布于 2024-09-25 02:34:41

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

相关问题 更多 >