简体   繁体   中英

Issue with dynamically populating dropdownlist for a field in django custom user registration form

I have created one custom user registration form in Django as follows:

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

Then in register.html I am populating dropdownlist for booth based on state she selects as follows:

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

        });

But the problem is that while submitting the form I am getting the following error message in UI:

Can please anyone suggest me what mistake I am doing here.

EDIT: In my views.py for handling registation form submission:

  @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,
)

Here in above view function I have checked form.is_valid() which is returning false. Can please anyone suggest me what mistake I am doing.

Booth value should be in queryset which you pass to the field - Booth.objects.none() - Now it's always empty.

You can dynamically change this queryset, something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM