Django checkbox field
16,291
The models.BooleanField
renders itself as a checkbox. Is either True
or False
. So:
# models.py
class Topic(models.Model):
# ...
public = models.BooleanField(default=True)
# forms.py
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ["text", "public"]
labels = {"text": "", "public": "label for public"}
If you want to also accept null
values, then you should use models.NullBooleanField
.
Author by
Milo.D
Know a bit of HTML/CSS and am looking to expand my knowledge on Javascript, JQuery, etc. Also having a look at a bit of Python, but not seriously
Updated on June 04, 2022Comments
-
Milo.D almost 2 years
I am trying to add a checkbox that if ticked will make a attribute in my model false.
My model is:
class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) public = False My forms.py (where the checkbox should go) is: class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''}
And my function:
def topics(request): """Show all topics.""" topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context)
Could you please tell me what I need to change in order that when a checkbox in forms is checked, the public variable becomes True, and then the function Topics displays public topics as well as just the owners.
Thanks
Milo
-
Soren over 4 yearsBut that field does not show up in the detailed view, right?
-
nik_m over 4 yearsIt does render as a checkbox in the detailed view. What makes you think otherwise?