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

Joy

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:

Select a valid choice. That choice is not one of the available choices

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.

Yablochkin

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Creating Custom user registration form Django

From Dev

Django custom registration form

From Dev

Django Registration Redux custom registration form

From Dev

Django User Registration Form KeyError

From Dev

Devise custom validation for a custom field in the registration form

From Dev

C# User Registration Form Issue

From Dev

Captcha field in plone user registration form

From Dev

Django - Add field to form dynamically

From Dev

django 1.7 User Registration form with profile picture

From Dev

Django user signup / registration form not working

From Dev

Adding custom user registration fields in django

From Dev

Added custom field to user registration but field does not push information to the database

From Dev

Added custom field to user registration but field does not push information to the database

From Dev

form.isValid() always return false in custom registration form django

From Dev

Adding custom field in default joomla 3.1.1 registration form

From Dev

Can't add custom field from registration form in AngularJS + Stormpath

From Dev

Having trouble adding a "custom" field to a Devise registration form

From Dev

Dynamically Add Field to Model Form Using Django

From Dev

Rails, use a form field to set something on the user registration (devise)

From Dev

php registration form issue

From Dev

Meteor - Cannot access custom user field upon registration

From Dev

Unicode issue updating User model with a custom Form

From Dev

Dynamic autocreate field issue on Django Form

From Dev

Re-populating form field

From Dev

Re-populating form field

From Dev

Django Registration Registration_form

From Dev

Django Form not saving when using a custom field

From Dev

Django custom user field clashes with AbstractBaseUser

From Dev

Django login form not working for custom user model

Related Related

  1. 1

    Creating Custom user registration form Django

  2. 2

    Django custom registration form

  3. 3

    Django Registration Redux custom registration form

  4. 4

    Django User Registration Form KeyError

  5. 5

    Devise custom validation for a custom field in the registration form

  6. 6

    C# User Registration Form Issue

  7. 7

    Captcha field in plone user registration form

  8. 8

    Django - Add field to form dynamically

  9. 9

    django 1.7 User Registration form with profile picture

  10. 10

    Django user signup / registration form not working

  11. 11

    Adding custom user registration fields in django

  12. 12

    Added custom field to user registration but field does not push information to the database

  13. 13

    Added custom field to user registration but field does not push information to the database

  14. 14

    form.isValid() always return false in custom registration form django

  15. 15

    Adding custom field in default joomla 3.1.1 registration form

  16. 16

    Can't add custom field from registration form in AngularJS + Stormpath

  17. 17

    Having trouble adding a "custom" field to a Devise registration form

  18. 18

    Dynamically Add Field to Model Form Using Django

  19. 19

    Rails, use a form field to set something on the user registration (devise)

  20. 20

    php registration form issue

  21. 21

    Meteor - Cannot access custom user field upon registration

  22. 22

    Unicode issue updating User model with a custom Form

  23. 23

    Dynamic autocreate field issue on Django Form

  24. 24

    Re-populating form field

  25. 25

    Re-populating form field

  26. 26

    Django Registration Registration_form

  27. 27

    Django Form not saving when using a custom field

  28. 28

    Django custom user field clashes with AbstractBaseUser

  29. 29

    Django login form not working for custom user model

HotTag

Archive