Django - 创建用于编辑模型的多个实例的表单

时间:2016-04-15 12:57:21

标签: python django forms

注意:Django / Python初学者,希望这个问题很清楚

我需要创建一个表单,可以在一个表单中一次编辑多个模型实例,并同时提交。

例如,我有两个模型,Invite和Guest,其中多个Guest可以与一个Invite关联。我需要一个表单,我可以编辑附加到邀请的所有访客的特定详细信息,同时提交,然后保存到数据库。

我已经看到了一些关于使用crispy-forms的建议,但是还没有设法让它发挥作用。

我创建了一个提供某些输入的表单:

from django import forms
from app.models import Guest


class ExtraForm(forms.ModelForm):
    diet = forms.CharField(max_length=128, required=False)
    transport = forms.BooleanField(initial=False)

    # An inline class to provide additional information on the form.
    class Meta:
        # Provide an association between the ModelForm and a model
        model = Guest
        fields = ('diet', 'transport')

我的观点包括:

def extra_view(request, code):
    invite = get_invite(code)
    # Get the context from the request.
    context = RequestContext(request)

    # Get just guests labelled as attending
    guests_attending = invite.guest_set.filter(attending=True)

    if request.method == 'POST':
        form = ExtraForm(request.POST)

        print(form.data)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            # form.save(commit=True)

            print(form)

            return render(request, 'weddingapp/confirm.html', {
                'invite': invite,
            })
        else:
            # The supplied form contained errors - just print them to the terminal for now
            print form.errors
    else:
        # # If the request was not a POST, display the form to enter details.
        GuestForm = ExtraForm()

    return render_to_response('weddingapp/extra.html', 
           {'GuestForm': GuestForm, 'invite': invite, 'guests_attending': guests_attending}, context)

最后,我的表格:

<form id="extra_form" method="post" action="{% url 'weddingapp:extra' invite.code %}">

    {% csrf_token %}

    {% for guest in guests_attending %}
        <fieldset class="form-group">
            <h3>Form for {{ guest.guest_name }}</h3>
            {% for field in GuestForm.visible_fields %}
                {{ field.errors }}

                <div>
                    {{ field.help_text }}
                    {{ field }}
                </div>
            {% endfor %}
        </fieldset>
    {% endfor %}

    {{ form.management_form }}
    <table>
        {% for form in form %}
            {{ form }}
        {% endfor %}
    </table>

    <input type="submit" name="submit" value="Submit"/>
</form>

任何建议

1 个答案:

答案 0 :(得分:3)

您需要使用FormSet,尤其是ModelFormSet

...
GuestFormSet = modelformset_factory(Guest, form=ExtraForm)

在您的视图中,您可以将其用作普通表单:

formset = GuestFormSet(data=request.POST)

if formset.is_valid():
  formset.save()

并在您的模板中:

   <form method="post" action="">
     {{ formset.management_form }}
       <table>
         {% for form in formset %}
           {{ form }}
         {% endfor %}
       </table>
   </form>

提示:您可以避免避免使用此样板

if request.method == 'POST':
    form = ExtraForm(request.POST)

    print(form.data)

    # Have we been provided with a valid form?
    if form.is_valid():

使用简单的快捷方式:

form = ExtraForm(data=request.POST or None)
if form.is_valid():
  ...