一页有两个链接[管理页面]。两者都进入相同的表单页面[添加帖子]。在管理页面中;您可以单击“新帖子”链接,也可以在连接到同一页面的文本框中输入您的标题[添加帖子]。在那个页面中;我有一个带有复选框字段的表单。
isdraft = forms.BooleanField(required=False,initial=True)
如你看到的 ; 我将字段的默认值设置为 True。如果我在管理页面点击“新帖子”;来到那个表格页面;效果很好。复选框对我来说是真实的。但是如果我使用其他方式[在文本框中输入标题]复选框对我来说是假的。我想不通。
编辑:我认为这个问题很复杂。不清楚。如果需要任何其他数据;我可以添加它。
编辑:
管理员.html:
<h1>Posts<a href="{% url add_post %}" class="button">New Post</a></h1> #this works!
<form action="{% url add_post %}" method="POST">{% csrf_token %}
{{ form.title }} <!-- this is textbox -->
{{ form.isdraft.as_hidden }} <!-- when i add this line form works correctly. but i get 'please fill all fields' warning when redirected to add_post page. -->
</form>
编辑2: add_post视图:
@login_required(login_url='/login/')
def add_post(request):
template_name = 'add.html'
owner = request.user
if request.method == "POST":
form = addForm(request.POST)
if form.is_valid():
titleform = form.cleaned_data['title']
bodyform = form.cleaned_data['body']
checkform = form.cleaned_data['isdraft']
n = Post(title=titleform, body=bodyform, isdraft=checkform, owner=owner)
n.save()
messages.add_message(request, messages.SUCCESS,
'New post created successfully!')
return HttpResponseRedirect('/admin/post/add/')
else:
messages.add_message(request, messages.WARNING,
'Please fill in all fields!')
else:
form = addForm()
return render_to_response(template_name, {'form': form, 'owner':owner,},context_instance=RequestContext(request))`
管理员视图:
@login_required(login_url='/login/')
def admin_view(request):
if request.session.get('loggedin') == "djangoo":
form = newDraft() # textbox in admin page
return render_to_response('admin.html', {'form':form },context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/login/')
添加表格:
class addForm(forms.Form):
title = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'placeholder':'Title here',}))
body = forms.CharField(widget=forms.Textarea(
attrs={'placeholder':'Write post here','rows':'25','cols':'90',}))
isdraft = forms.BooleanField(required=False,initial=True)