user11684966
user11684966

Reputation:

Django - hide "This field is required." for BooleanField

I only want to display a checkbox the user has to click in order to confirm that notice has been taken:

class CheckForm(forms.Form):
    confirmed = forms.BooleanField(required=True)

    def __init__(self, *args, **kwargs):
        super(CheckForm, self).__init__(*args, **kwargs)
        self.fields['confirmed'].label = 'I confirm that I have taken notice'

The problem now is that my form shows the following label: "This field is required." at the template output. This is also making sense as I call the form like so at my views.py:

form = CheckForm(request.POST)

Is there any workaround to only hide the mentioned label at my template and keep required=True? Simply doing required=False at forms.py or removing request.POST from views.py is not a solution as this Field is per definition required and "if form.is_valid():" does not validate if request.POST is missing

views.py

def check(request):
    form = CheckForm(request.POST)
    user = User.objects.get(user=request.session.get('user'))
    if request.method == 'POST':
        if form.is_valid():
            user.token_checked = True
            user.save()
            messages.success(request, 'Thanks for your check-up, you are now able to login again.')
            return redirect(reverse('login'))
        else:
            return render(request, 'check.html')
    else:
        if not user.token_checked:
            username = str(user)
            token = str(user.reset_token)
            args = {
                'token': token,
                'username': username,
                'form': form
            }
            return render(request, 'check.html', args)

Upvotes: 0

Views: 1064

Answers (2)

user11684966
user11684966

Reputation:

Found a solution that is acceptable, I simply do:

self.fields['reset_token'].error_messages = {'required': 'My custom message to display'}

This sadly does not fully hide the message but at least it's acceptable if you only want the user to acknowledged some terms of your site/service.

Upvotes: 0

Işık Kaplan
Işık Kaplan

Reputation: 2992

Required for a BooleanField does not make sense. A BooleanField can either be true of false, and the representation of false in html forms is an empty checkbox, which is well: empty. See the docs.

Upvotes: 0

Related Questions