Reputation: 365
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
Upvotes: 4
Views: 24854
Reputation: 12086
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
.
Upvotes: 17