0

I would like to create a form that contains several fields like this

class MainForm(forms.Form):
    name = forms.CharField(label='name')
    comment = forms.CharField(label='comment')

Right now we have one field "comment". Now I want to have the option that a user can add more comment fields to the form through the website.

So I need to:

1) Define the form more flexible such that there can be N comment fields. (Default is N=1)

2) Define a method to add new comment fields.

3) Define utility functions, like cleaning form fields, so flexible that they can handle the dynamic number of comment fields.

I would like get some ideas of how to set this up in a clean way.

4

2 回答 2

1

Formsets 是一个很好的解决方案:

https://docs.djangoproject.com/en/1.6/topics/forms/formsets/

它将干净地处理 1 和 3。过去,我不得不编写 javascript 在单击添加时在表单中注入额外的字段。然后在提交后 django 负责其余的工作。

于 2014-06-27T15:49:48.020 回答
1

所以我找到了一些对我有用的东西,我想至少发布我所做的粗略草稿。

首先,我确实发现 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>
于 2014-07-15T14:01:08.693 回答