Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django checkbox field

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

like image 788
Milo.D Avatar asked Nov 16 '25 01:11

Milo.D


1 Answers

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.

like image 58
nik_m Avatar answered Nov 17 '25 20:11

nik_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!