【发布时间】:2013-03-22 21:10:44
【问题描述】:
我正在制作一个 Web 应用程序,它将在表格中显示学生列表,并在每个名称旁边有一个输入字段,允许用户为该学生提供“标签”。我无法弄清楚如何将这一切集成到一个表中。
这是我在 forms.py 中声明的表单:
class TagsForm(forms.Form):
def __init__(self, *args, **kwargs):
applicants = kwargs.pop('applicants')
super(TagsForm,self).__init__(*args, **kwargs)
for i, applicant in enumerate(applicants):
self.fields['tag_%s' % i] = forms.CharField(label=applicant)
def tagInput(self):
for tags in self.cleaned_data.items():
if tags.startswith('tag_'):
yield (tags)
然后在 view.py 中创建表单并将其传递到上下文中:
tags_form = TagsForm(request.POST or None, applicants=applicantQuery)
if tags_form.is_valid():
for(tags) in tags_form.tagInput():
...
...
context = Context({'tagsForm':tags_form, ... }
return render_to_response('review/assignment.html', context)
如您所见,我正在尝试为我将在表格中显示的每个申请人创建一个字符输入“标签”字段。然后在我的模板中我有这个:
<form name="applicants" method="POST">
<table class="sortable" id="appTable">
<tr>
<th>EID</th>
<th>Name</th>
<th>Reviewer Tags</th>
</tr>
{% for applicant in applicants %}
<tr>
<td> <a href="../../{{ applicant.app_id }}/overview" target="_blank">{{ applicant.app_eid }}</a></td>
<td> {{ applicant.app_displayName }} </td>
<td> {{ tagsForm.tags_???}} </td>
</tr>
{% endfor %}
</table><br />
{{ tags_form.non_field_errors }}
<input type="submit" value="Submit Tags"/>
</form>
我不确定如何遍历 tagsForm tags 字段,因为我已经遍历了申请者。我对 Django/HTML 很陌生,所以解决方案可能很简单,但是我搜索并找不到任何试图做这样的事情的人。感谢您的帮助。
【问题讨论】:
-
每个申请人都有一个标签?你把它存放在哪里?
-
在views.py中,一旦我们从tagInput获得响应,它将被存储在数据库表中。
-
在它自己的桌子上?他们有关系吗?标记似乎应该是 m2m 关系,在这种情况下,您可以简单地使用 ManyToManyField
-
我的意思是这并不是我真正遇到的问题,我在模板文件中显示输入字段时遇到了问题。
标签: python html django forms dynamic