我在从数据库获取数据后尝试在表单中显示一些复选框。 如果某些内容是公开的,我会设置一些字段。该复选框始终为“未选中”。
我的班级:
class PrivacyForm(forms.Form):
geburtsdatum=forms.CheckboxInput()
strasse=forms.CheckboxInput()
plz=forms.CheckboxInput()
ort=forms.CheckboxInput()
land=forms.CheckboxInput()
fon=forms.CheckboxInput()
我的方法:
@login_required
def edit_privacy(request,template_name='user/edit_privacy.html'):
user=Users.objects.get(id_u=request.user.id)
if request.method=='POST':
form=PrivacyForm(request.POST)
if form.is_valid():
#
render_to_response('user/public_profil.html',{'profil':user},context_instance=RequestContext(request))
else:
msg="make sure all fields are entered and valid"
else:
#form
form=PrivacyForm()
msg="Select what you want to be public"
return render_to_response(template_name,{'form':form,'profil':user,'msg':msg},context_instance=RequestContext(request))
和我的表格:
{% extends "home/portal.html" %}
{% block body %}
<h3>::::: PRIVATSPHÄRE :::::</h3>
{{msg}}
<form id="formSearch" action="/user/privacy/" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Speichern" class="button"/>
</form>
{% endblock %}
任何帮助将不胜感激。谢谢:))
答案 0 :(得分:2)
我不确定您是如何使用此表单的,但这样可行:
class PrivacyForm(forms.Form):
geburtsdatum=forms.BooleanField()
strasse=forms.BooleanField()
plz=forms.BooleanField()
ort=forms.BooleanField()
land=forms.BooleanField()
fon=forms.BooleanField()
然后在视图代码中,您可以设置初始值:
form=PrivacyForm(initial={'geburtsdatum': True,
'strasse': True,...})
会将指定的复选框呈现为已选中(如果为“True”)或未选中(如果为“False”)..
答案 1 :(得分:1)
你可以在这里查看!
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
class PrivacyForm(models.Model):
pass
form = PrivacyForm(object_provacy_model_item)