让用户可以选择公开主题。这个会 需要一个名为public的属性作为Topic模型的一部分(默认情况下应该设置为False)和new_topic页面上的一个表单元素,允许用户将主题从私有更改为public [在此输入链接描述] [1]
from django.db import models
from django.contrib.auth.models import User
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)
def __str__(self):
"""Return a string representation of the model."""
return self.text
class Entry(models.Model):
"""Something specific learned about a topic."""
topic = models.ForeignKey(Topic)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""Return a string representation of the model."""
return self.text[:50] + "..."enter code here
答案 0 :(得分:0)
您只需将其添加为Topic
型号上的字段:
public = models.BooleanField(default=False)
然后将其添加到TopicForm
的字段列表中,它将自动呈现在表单上:
fields = ['text', 'public']
答案 1 :(得分:-1)
我也陷入了困境。我有模板上的表单元素的解决方案。我已经像复选框那样实现了它:
new_topic.html
<label><input type="checkbox" name="public"/> Public</label>
我通过添加元属性 public :
编辑了forms.pyforms.py
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
public = forms.BooleanField(required=False)
在new_topic函数下的views.py中,我添加了复选框检查:
@login_required
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(request.POST)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user
if request.POST["public"]:
new_topic.public = True
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
单击复选框时,属性public已正确更改为true,但我无法覆盖该主题的@login_required。确切地说,新创建的主题不公开。如果有人在这一点上有解决方案,那就太棒了