我正在尝试添加一个复选框,如果勾选将使我的模型中的属性为false。
我的模特是:
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': ''}
我的功能:
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)
请您告诉我需要更改的内容,以便在选中表单中的复选框时,公共变量变为True,然后功能主题显示公共主题以及仅显示所有者。
由于
米洛
答案 0 :(得分:5)
models.BooleanField
呈现自己as a checkbox。是True
还是False
。所以:
# 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"}
如果您还想接受null
值,则应使用models.NullBooleanField
。