所以我找到了一些对我有用的东西,我想至少发布我所做的粗略草稿。
首先,我确实发现 percent20 的使用 django formsets 的建议非常有帮助。我的 forms.py 大致如下所示:
from django import forms
from django.forms.formsets import formset_factory
from django.forms.forms import NON_FIELD_ERRORS
class CommentForm(forms.Form):
comment = forms.CharField(label='comment')
class MainForm(forms.Form):
name = forms.CharField(label='name')
def __init__(self):
self.commentFormset = formset_factory(CommentForm, extra=1)
self.comments = self.commentFormset()
def clean(self):
cleaned_data = super(MainForm, self).clean()
for nForm, commentForm in enumerate(self.comments):
if commentForm.is_valid():
pass
else:
self._errors[NON_FIELD_ERRORS] = self.error_class(['Invalid Comments'])
这是我的views.py的相关部分
from forms import MainForm
def commentView(request):
if request.method == 'POST':
form = MainForm(data=request.POST)
form.comments = form.commentFormset(data=request.POST)
if form.is_valid():
# ...
for commentForm in form.comments:
if commentForm.is_valid():
# do some stuff with each comment
else:
form = MainForm()
template = loader.get_template('main.html')
context = RequestContext(request, { 'form': form })
return HttpResponse(template.render(context))
我发现了以下很棒的 jquery 插件:http: //blog.stanisla.us/2009/10/10/jquery-plugin-django-dynamic-formset/。
这使我能够让用户有机会添加和删除评论字段。view.py 或 forms.py 中不需要额外的代码。
这是我的模板中的相关片段。
<script type="text/javascript" src="{{ STATIC_URL }}jquery.formset.js"></script>
<script type="text/javascript">
$(function() {
$('tr.comment-form').formset( { prefix: 'form' });
})
</script>
<div id="commentSection">
Comments:
<table>
<tbody>
{{ form.comments.management_form }}
<th>Comment</th><th></th>
{% for commentForm in form.comments %}
<tr class="comment-form">
<td>{{ commentForm.comment.errors }}{{ commentForm.comment }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>