How to Insert a Checkbox in a Django Form

How to insert a checkbox in a django form

models.py:

class Settings(models.Model):
receive_newsletter = models.BooleanField()
# ...

forms.py:

class SettingsForm(forms.ModelForm):
receive_newsletter = forms.BooleanField()

class Meta:
model = Settings

And if you want to automatically set receive_newsletter to True according to some criteria in your application, you account for that in the forms __init__:

class SettingsForm(forms.ModelForm):

receive_newsletter = forms.BooleanField()

def __init__(self):
if check_something():
self.fields['receive_newsletter'].initial = True

class Meta:
model = Settings

The boolean form field uses a CheckboxInput widget by default.

How to add Checkboxes in Django Form.

You can easily achieve that using checkbox widget in django forms.

Define your form class as :

NGO_CHOICES = (
('one', 'ONE'),
('two', 'TWO'),
('three', 'THREE'),)

class UserForm(forms.ModelForm):
ngo = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=NGO_CHOICES)

class Meta():
model = User
fields = ('ngo', 'email','first_name','last_name','username')

Now while saving the data, you can access the data of checkbox in

if request.method =="POST" :
user_form = UserForm(data=request.POST)

if user_form.is_valid():
# getting the list of ngos
ngo = user_form.cleaned_data['ngo']
user = user_form.save()
user.save()

registered = True

else:
print(user_form.errors)

else:
user_form = UserForm()

Hope it helps.

How to pass checkbox field to forms in django

I would recommend using the default modelchoicefield for foreignkey relations which will give you a select box in your template. Javascript is not my best programming language but here's an answer on how to set this up:

models.py

from django.db import models


class School(models.Model):
name = models.CharField(max_length=255)

def __str__(self):
return self.name


class Students(models.Model):
school = models.ForeignKey(School, on_delete=models.CASCADE)
name = models.CharField(max_length=200, unique=True, help_text="Student's name")

def __str__(self):
return self.name

forms.py

from django import forms

from .models import Students


class StudentsForm(forms.ModelForm):
school = forms.CharField(widget=forms.HiddenInput)

class Meta:
model = Students
fields = ("name", "school")

views.py

from django.urls import reverse_lazy
from django.views.generic import FormView

from .forms import StudentsForm
from .models import Students, School


class StudentView(FormView):
template_name = 'add_student.html'
model = Students
form_class = StudentsForm
success_url = reverse_lazy('students')

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['schools'] = School.objects.all()
return context

add_student.html

<form>
{{ form.as_p }}

<ul class="school__list">
{% for school in schools %}
<li class="school__list-item">{{ school.name }}
<input type="checkbox" class="school__list-item-checkbox"
value="{{ school.id }}" name="school"/>
</li>
{% endfor %}
</ul>
</form>

<script>
const schools = document.querySelectorAll('.school__list-item-checkbox');
for (let i = 0; i < schools.length; i++) {
schools[i].addEventListener('click', () => {
{# populate the hidden school field with the value that is checked here. #}
})
}
</script>

How can I implement a check box in django

You can do this.

in template:

<form method='post'>
<input type="checkbox" name="use_stages" value="1">Use stages
<input type="submit" value="submit">
</form>

views.py

def home(request):
if request.method == 'POST':
check = request.POST.get('use_stages', 0)
print(check) # 1 (True) or 0 (False)

context = {

}
url = 'boards/home.html'
return render(request, url, context)

if checkbox is check, value of check will be 1 otherwise 0. You can use this as True (1) or False (0)

How to check the checkbox state then show/hide the next input field in Django template

you can use conditions in Django templates check this article

so your template should be something like this:

 <div class="form-group col-md-6">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.is_scholorship.errors }}
<label class="form-label">獎學金</label>
{{ form.is_scholorship }}
<button type="button" onclick="test()"> 測試 </button>
</div>

</div>
{% if form.is_scholarchip %}
<div class="form-group col-md-6">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.scholorship_amount.errors }}
<label class="form-label">獎學金金額</label>
{{ form.scholorship_amount }}
</div>

</div>
{% endif %}

How to access the checkbox data in Django form

You can access in your view all data from your forms.
Just print request.POST to see wich checkbox is selected.

How do I use checkboxes to pass value to views django?

You could you HTML Checkboxes like this:

<p>Choose your monster's features:</p>

<div>
<input type="checkbox" id="scales" name="scales"
checked>
<label for="scales">Scales</label>
</div>

<div>
<input type="checkbox" id="horns" name="horns">
<label for="horns">Horns</label>
</div>

Basically this is just a input field with the type checkbox. You also could use Django input fields:

https://docs.djangoproject.com/en/3.2/ref/forms/

This is the source of my code:

https://developer.mozilla.org/de/docs/Web/HTML/Element/input/checkbox

Mozialla is a good choice in general if you have any questions about html, javascript or css

In django form how to add checkboxes instead of radio button?

You can use the MultipleChoiceField in Django. https://docs.djangoproject.com/en/1.10/ref/forms/fields/#multiplechoicefield

If the choices that the user can select are coming from a model then you can use the ModelMultipleChoiceField and pass a queryset for the choices. check https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelmultiplechoicefield



Related Topics



Leave a reply



Submit