【发布时间】:2011-12-30 17:55:04
【问题描述】:
我想创建一个页面,其中包含用户列表和复选框,以表明用户是否被选中,这将对所选用户应用一些操作。 我创建了一个如下所示的表单类:
#in forms.py
class UserSelectionForm(forms.Form):
"""form for selecting users"""
def __init__(self, userlist, *args, **kwargs):
self.custom_fields = userlist
super(forms.Form, self).__init__(*args, **kwargs)
for f in userlist:
self.fields[str(f.id)] = forms.BooleanField(initial=False)
def get_selected(self):
"""returns selected users"""
return filter(lambda u: self.fields[str(u.id)], self.custom_fields)
在我的模板中,我在表格中列出了用户,我希望该表格的最后一列是那些复选框。我需要根据它们的名称一一呈现字段。 我尝试创建一个模板标签,该标签将返回所需表单元素的 html 代码:
#in templatetags/user_list_tags.py
from django import template
register = template.Library()
#this is django template tag for user selection form
@register.filter
def user_select_field(form, userid):
"""
returns UserSelectionForm field for a user with userid
"""
key = std(userid)
if key not in form.fields.keys():
print 'Key %s not found in dict' % key
return None
return form.fields[key].widget.render(form, key)
最后,模板代码如下:
<form action="" method="post">
{% csrf_token %}
<table class="listtable">
<tr>
<th>Username</th>
<th>Select</th>
</tr>
{% for u in userlist %}
<tr>
<td>{{u.username}}</td>
<td>{{select_form|user_select_field:u.id}}</td>
</tr>
{% endfor %}
</table>
<p><input type="submit" value="make actions" /></p>
但是,这不会将这些小部件绑定到表单,因此,在提交表单后,验证会失败。错误消息说所有自定义字段都是必需的。 所以这是我的问题:
渲染单独的表单域的正确方法是什么?
创建这种带有复选框的表单的正确方法是什么? (我的意思是也许我的方法很愚蠢,有一种更简单的方法可以实现我想要的。
【问题讨论】:
-
也许你应该尝试用一点 javascript 来做这个。
-
我不想在这个阶段的项目中使用 javascript。但是,我究竟应该怎么做?或者我应该谷歌什么?你知道我不是一个巨大的 javascript pro=)
标签: python django django-forms django-templates django-template-filters