Search code examples
djangodjango-modelsdjango-formsdjango-model-field

Every field in Django modelform shows "Select a valid choice. That choice is not one of the available choices."


I've already read many other threads complaining about this error message but I still can't figure this out. I try removing the fields that give the error, and the error message just moves to another field the next time I try to submit. They are CharField, Foreign Key, and other types.

forms.py

class TemporaryresponseForm(forms.ModelForm):    
    gender_custom = forms.CharField(
        required=False,
        label="",        
    )

    ethnicity = forms.ModelChoiceField(
        queryset=Ethnicity.objects.all(),
        widget=forms.RadioSelect(),
        empty_label=None,
        required=True,
        label="Which of the following best describes your ethnicity?"
    )
...
class Meta:
        model = Temporaryresponse
        fields = [...'gender_custom', 'ethnicity',...]

views.py

def tr(request):
    if request.method == "POST":
        form = TemporaryresponseForm(request.POST)
        if form.is_valid():
            tempresponse = form.save(commit=False)
            tempresponse.ip = "123456"
            tempresponse.save()
            return redirect('politicalpollingapp/index.html')
    else:
        form = TemporaryresponseForm()
    return render(request, 'politicalexperimentpollapp/tr.html', {'form': form})


def nr(request, pk):
    return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse})

tr.html template

{% extends 'politicalexperimentpollapp/base.html' %}
{% block extrahead %}
{% load crispy_forms_tags %}
{{ form.media }}
{% endblock extrahead%} 
...
<form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <div><br></div>

        <div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div>
    </form>
..

models.py

class Ethnicity(models.Model):
    ethnicity = models.CharField(max_length=200)

    def __str__(self):
        return '%s' % (self.ethnicity)
...
class Temporaryresponse(models.Model):
    birth_year = models.PositiveIntegerField()
    voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True)
    party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True)
    gender = models.ForeignKey(Gender, models.SET_NULL, null=True)
    gender_custom = models.CharField(max_length=200, blank=True)
    ethnicity = models.ForeignKey(Ethnicity, models.SET_NULL, null=True)
    race = models.ManyToManyField(Race)
    zip_code = models.IntegerField()
    ip = models.CharField(max_length=200, blank=True)
    policy_areas_of_importance = models.ManyToManyField(Policy_category, blank=True)
    likelihood_of_voting = models.PositiveIntegerField(models.SET_NULL, null=True, blank=True)

Oddly no error shows up in my Chrome console - it's only because I am showing errors on the actual page. I'm not sure if that's normal. Thanks in advance for any help, I'm ripping my hair out at this point.


Solution

  • I discovered that I was using the wrong language for the "race" form field. I had used ModelChoiceField but it should be ModelMultipleChoiceField as follows:

    race = forms.ModelMultipleChoiceField(queryset=Race.objects.all(), widget=forms.CheckboxSelectMultiple, label="5. Which of the following best describes your race? Please select all that apply.")