Reputation: 321
In my html, I have the code below
...
<div class="tab-pane fade" id="account-notifications">
<div class="card-body pb-2">
<h6 class="mb-4">Activity</h6>
<div class="form-group">
<label class="switcher">
<input type="checkbox" class="switcher-input" name="new_comment_on_my_article" id="new_comment_on_my_article" checked>
<span class="switcher-indicator">
<span class="switcher-yes"></span>
<span class="switcher-no"></span>
</span>
<span class="switcher-label">Email me when someone comments on my article</span>
</label>
</div>
<div class="form-group">
<label class="switcher">
<input type="checkbox" class="switcher-input" name="new_answer_on_my_forum_thread" id="new_answer_on_my_forum_thread">
<span class="switcher-indicator">
<span class="switcher-yes"></span>
<span class="switcher-no"></span>
</span>
<span class="switcher-label">Email me when someone answers on my forum thread</span>
</label>
</div>
</div>
</div>
...
There are two input fields, one is checked and the other one isn't. The user can also toggle On or Off the switch. My problem how to get the current state of the switch (toggled On or Off) so that I can send the value to my Django as True or False
Upvotes: 0
Views: 300
Reputation: 8202
I may be missing something, but don't you just have to give your <input>
fields names, so that when the form is submitted, their status comes back in the POST data?
<form ...>
...
<input type="checkbox" class="switcher-input" name="foo_switch">
</form>
then in your view,
# IIRC checked boxes come back as "on" and unchecked ones don't come back
# memory might be incorrect
foo_switch = request.POST.get('foo_switch', 'off')
status = ( foo_switch == 'on')
You could also define a forms.BooleanField
, but manually render the form fields. Then the <input>
element's HTML is completely under your control, but Django form processing handles obtaining the True/False value.
Upvotes: 1