unselect value from form.select


I’m using a widget=forms.Select which presents a list of available choices based on a FK to choices model.

The select box has a default value of ------- If i change a previouly selected choice back to the default ------ i get the error:
could not be changed because the data didn't validate. I understand why as this ------ is not a valid option.

What is the best way to fix this, ideally i want to be able have blank values and have set this on the model to (blank=True) So is there a way to overwrite the ------ with a blank value?


For a ForeignKey field, you would want null=True.

Hi Ken,

I’ve already got null=True
This is the error The ProjectQuestionnaireAnswer could not be changed because the data didn't validate. which is calling out the ProjectQuestionnaireAnswer model


class ProjectQuestionnaireAnswer(models.Model):
    YN_Choices = [
        ('Yes', 'Yes'),
        ('No', 'No'),
        ('Unknown', 'Unknown')
    question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE)
    answer = models.ForeignKey(Choice, on_delete=models.CASCADE,null=True, blank=True)
    value = models.CharField(max_length=20, blank=True)
    notes = models.TextField(blank=True)
    response = models.ForeignKey(ProjectQuestionnaireResponse, on_delete=models.CASCADE)

Or do i need to add this to the Choice model.
choice_text = models.CharField(max_length=200) ?

Is required = False for answer in your form?

[edit] No, this issue does not affect your Choice model.

I dont have that set, but im not sure where i need to set this:

class AnswerForm(ModelForm):
    answer = forms.CharField(required=False) # just added, but hasn't helped :(

    class Meta:
        model = ProjectQuestionnaireAnswer
        fields = ('answer','notes')

        widgets = {
            'notes': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Add notes to question here'}),

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        question_id = kwargs.pop('question_id')
        super().__init__(*args, **kwargs)
        self.fields['answer'] = forms.ModelChoiceField(
            widget=forms.Select(attrs={'class': 'form-control select2'})


conflicts with this:

You need to add the required=False to the parameters in your ModelChoiceField definition. (And remove the unnecessary field definition at the class level.)

1 Like

Thank you, Ken. Worked perfectly