How to write a text/statement at the right of the BooleanField in Django Form?

Hi there,

I have a form that has an agreement checkbox field which uses Django’s BooleanField. It works fine, but it shows the text on the left side of the checkbox, like below:

but, I want it to show a text/statement at the right side of the checkbox and want the left side empty, something like below:
image

How do I achieve this behavior?

Probably the easiest way to do this as a “one-off” would be to define that form field as having no label and then render the desired text after the form field.

(If this is just a sample of a more general need, then you might want to look into custom widget rendering.)

@KenWhitesell yes, I have couple of these kinds of checkboxes, so I want same behavior for all of them. How do I use the custom widget to achieve this behavior? I read the Django documentation, but did not find anything useful. Can you refer me to any guide or show me an example? BTW, the form code is below:

class InviteAgreeForm(forms.Form):
    agreement = forms.BooleanField(required=True)

Also can you tell me how do I render a text after the form field? Do I need to do it using HTML? Or pass the text to the template via context from view and then use that text in template?

Unfortunately, I can’t - it’s not something I do so I haven’t really gathered any resources along those lines.

Easiest way is in the template.

Actually, I need to correct my earlier response. (This really isn’t a topic I follow closely…)

Looking at Rendering fields manually, it may be as easy as changing this:

<div class="fieldWrapper">
    {{ form.agreement.errors }}
    {{ form.agreement.label_tag }}
    {{ form.agreement }}
</div>

to this:

<div class="fieldWrapper">
    {{ form.agreement.errors }}
    {{ form.agreement }}
    {{ form.agreement.label_tag }}
</div>

In which case you would still want to have the label attribute on that field.

(For the record, what I was originally thinking of was this:)

<div class="fieldWrapper">
    {{ form.agreement.errors }}
    {{ form.agreement }}
    I agree to the Dropbox Terms
</div>
2 Likes

Currently, I am not using any CSS Framework like Bootstrap etc, so as per the documentation, would class="fieldWrapper" work or template will skip this?

I don’t understand what you’re asking here.

A template being rendered doesn’t know anything about CSS. The templates are being rendered in the server. The CSS gets applied to the HTML after it has been sent to the browser.

Well, how would the template know where to find the "fieldWrapper’ class that is being passed in the div tag as an attribute?

The template doesn’t - nor does it care. It’s just an attribute on an html element. The template rendering engine doesn’t do anything with CSS.

1 Like