问题描述
我正在尝试创建一个项目,在该项目中您可以创建主题,对于未经身份验证的用户可以是私有的或公开的.然后,您可以在每个主题中输入多个条目,以应用于该主题.现在,我正在尝试在我的 new_topic.html
中选中一个复选框,如果选中该复选框,它将计算为True,否则为False.但是,当我选中该复选框时,我无法使该复选框的评估结果为True.出于某种原因,页面中有两个适用于 new_topic.html
的复选框.一个带有标签,另一个带有一个盒子.
I'm trying to make a project, where you can make topics, that can be private or public to unauthenticated users. In every topic, you can then make several entries, applying to that topic. Now I'm trying to make a checkbox in my new_topic.html
, where if you check it, it evaluates to True, if not, to False. But I'm having trouble with making the checkbox evaluate to True, when I check it. And for some reason, there is two checkbuttons in the page that applies to new_topic.html
; one with a label, and one with just a box.
- 我尝试重新创建
db.sqlite3
数据库.但这没用. - 在保存new_topic变量时,我尝试在
new_topic()
函数中使用request.POST.get('public',False)
.¨
- I've tried recreating the
db.sqlite3
database. But that didn't work. - I've tried using
request.POST.get('public', False)
in mynew_topic()
function, when saving the new_topic variable.¨
代码
我的 learning_logs/models.py
看起来像这样:
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)
public = models.BooleanField(default=False)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
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, on_delete=models.CASCADE)
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."""
# Add an ellipsis ONLY if the entry,
# is more than 50 characters long.
if self.text > self.text[:50]:
return self.text[:50] + "..."
elif self.text <= self.text[:50]:
return self.text[:50]
我的 learning_logs \ views.py
看起来像这样:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from .models import Topic, Entry
from .forms import TopicForm, EntryForm
def index(request):
"""The Home Page for Learning Log."""
return render(request, 'learning_logs/index.html')
def check_topic_owner(request, topic):
"""Checks if the topic requested, is requested by the owner.
Else return Http404.
"""
if topic.owner != request.user:
raise Http404
@login_required
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)
@login_required
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = get_object_or_404(Topic, id=topic_id)
# Make sure the Topic belongs to the current user.
check_topic_owner(request, topic)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
@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(data=request.POST)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
@login_required
def new_entry(request, topic_id):
"""Add a new entry for the particular topic."""
topic = get_object_or_404(Topic, id=topic_id)
check_topic_owner(request, topic)
if request.method != 'POST':
# No data submitted; create a blank form.
form = EntryForm()
else:
# POST data submitted; process data.
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
if new_entry.topic.owner == request.user:
new_entry.save()
else:
return Http404
return HttpResponseRedirect(reverse('learning_logs:topic',
args=[topic_id]))
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
@login_required
def edit_entry(request, entry_id):
"""Edit an existing entry."""
entry = get_object_or_404(Entry, id=entry_id)
topic = entry.topic
check_topic_owner(request, topic)
if request.method != 'POST':
# Initial request; pre-fill form with the current entry.
form = EntryForm(instance=entry)
else:
# POST data submitted; process data.
form = EntryForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs:topic',
args=[topic.id]))
context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)
我的 learning_logs \ forms.py
看起来像这样:
from django import forms
from .models import Topic, Entry
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
我的 learning_logs \ templates \ learning_logs \ new_topic.html
看起来像这样:
{% extends "learning_logs/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>New topic:</h2>
{% endblock header %}
{% block content %}
<h1>Add a new topic:</h1>
<form action="{% url 'learning_logs:new_topic' %}" method='post'
class="form">
{% csrf_token %}
{% bootstrap_form form %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value=True id="public">
<label class="form-check-label" for="public">
Make it public?
</label>
</input>
</div>
{% buttons %}
<button name="submit" class="btn btn-primary">Add Topic</button>
{% endbuttons %}
</form>
{% endblock content %}
我似乎无法解决此错误.提前致谢!感谢您的帮助.
I just can't seem to fix this error. Thanks in advance! Any help is appreciated.
推荐答案
您拥有:
<input class="form-check-input" type="checkbox" value=True id="public">
<label class="form-check-label" for="public">
Make it public?
</label>
</input> # <<< this closing tag is wrong
正确的 input
标记:
<input class="form-check-input" type="checkbox" value=True id="public" />
因此,您将拥有:
<label class="form-check-label" for="public">
Make it public?
</label>
<input class="form-check-input" type="checkbox" value=True id="public" />
这篇关于Django-如何使您创建的主题公开?学习日志项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!