Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : Django 'ChoiceField' object has no attribute 'use_required_attribute'

Here's my model (in models.py)

class Score(models.Model):

    ROUTINETYPE_CHOICE = (
        (0, 'R1'),
        (1, 'R2'),
        (2, 'F'),
    )

    routineType = models.IntegerField(choices=ROUTINETYPE_CHOICE)
    pointA = models.DecimalField(max_digits=3, decimal_places=1)
    pointB = models.DecimalField(max_digits=3, decimal_places=1)
    pointC = models.DecimalField(max_digits=5, decimal_places=3)

And here's my Form (in forms.py)

class ScoreForm(forms.ModelForm):

    class Meta:
        ROUTINETYPE_CHOICE = (
            (0, 'R1'),
            (1, 'R2'),
            (2, 'F'),
        )

        model = Score
        fields = ('routineType', 'pointA', 'pointB', 'pointC')

        widgets = {
            'routineType': forms.ChoiceField(choices=ROUTINETYPE_CHOICE),
            'pointA': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}),
            'pointB': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}),
            'pointC': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}),
        }

And my view is usual:

def score_create(request):

    if request.method == 'POST':
        form = ScoreForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/score/')

    else:
        form = ScoreForm()

    context = {'form': form}
    return render(request, 'score_create.html', context)

When I try to display my form, django give me this error:

'ChoiceField' object has no attribute 'use_required_attribute'

The use_required_attribute is new in Django 1.10 and I've the possibility to set it to False. But it's on the Form level, it will say that my other fields are loosing the HTML required attribute too.

I've only three possibilities (with no "dummy" default option selected, like "choose…"), so my ChoiceField have always an option selected and then the HTML attribute "required" is fulfilled.

Someone know an another solution (other than set use_required_attribute=False) ?

like image 902
Gregg Avatar asked Oct 17 '22 09:10

Gregg


1 Answers

Thank Daniel. It was not a very detailed answer but, you'r right.

widgets = {
    'routineType': forms.Select(attrs={'class': 'form-control col-sm-2'}),
    'pointA': forms.TextInput(attrs={'class': 'form-control col-sm-2', 'placeholder': 'xx,xx', 'value': '0'}),
    'pointB': forms.TextInput(attrs={'class': 'form-control col-sm-2', 'placeholder': 'xx,xx', 'value': '0'}),
    'pointC': forms.TextInput(attrs={'class': 'form-control col-sm-2', 'placeholder': 'xx,xx', 'value': '0'}),
    }

And it's works !

like image 143
Gregg Avatar answered Oct 22 '22 09:10

Gregg