同时使用两种表格

时间:2015-10-09 19:16:33

标签: django django-forms django-templates

我想在模板中提交两个表单。原因是,我有两个单独的模型,每个模型都有一个模型形式,我必须同时提交以创建所需的结果:

我有以下两种形式:

class BootstrapModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(BootstrapModelForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
            })

class DeckForm(ModelForm):
    class Meta:
        model = Deck
        exclude = ('dust',)

class GuideForm(BootstrapModelForm):
    class Meta:
        model = Guide
        exclude = ('author', 'upvotes', 'downvotes', 'release_date', 'modified', 'deck')

    def __init__(self, *args, **kwargs):
        super(GuideForm, self).__init__(*args, **kwargs)
        self.fields['title'].label = 'Title of your AWESOME Guide!'
        self.fields['public'].label = 'Check, when you want to make your guide public'
        self.fields['public'].widget.attrs.update({
            'class': 'checkbox'
        })
        self.fields['introduction'].label = 'Introduction (not required, but recommended)'

甲板是创建指南的一部分。由于用户在编写指南时应该能够创建他自己的套牌,我需要两种形式。

在我的观点中,我这样处理:

def guide_create(request):
    if request.method == "POST":
        deck_form  =  DeckForm(request.POST)
        guide_form = GuideForm(request.POST)
        if guide_form.is_valid() and deck_form.is_valid():
            new_deck  = deck_form.save(commit=False)
            new_deck.dust = 0
            new_deck.save()

            new_guide = deck_form.save(commit=False)
            new_guide.author = Account.objects.get(id=request.user.id)
            new_guide.deck = Deck.objects.get(id=new_deck.id)
            new_guide.save()
        else:
            print(guide_form.errors)
            print(deck_form.errors)
    else:
        deck_form = DeckForm(prefix = 'DeckForm')
        guide_form = GuideForm(prefix = 'GuideForm')

    return render(request, 'hsguides/guide_create.html', {
        'DeckForm': DeckForm,
        'GuideForm': GuideForm,
    })

我使用commit=False所以我仍然可以在指南中插入套牌。现在我的问题在于创建模板。当我用当前设置提交表格时,我不再收到任何错误,但指南和套牌也没有保存!

<div style="width: 60%; margin: 0 auto;">

  <form class="form-horizontal" method="POST" action="{% url 'GuideCreate' %}"> {% csrf_token %}
    <fieldset>
      {% for field in DeckForm %}
        {% if field.errors %}
          <div class="class-group error">
            <label class="control-lable">{{ field.label }}</label>
            <div class="controls">{{ field }}
              <span class="help-inline">
                {% for error in  field.errors %}{{ error }}{% endfor %}
              </span>
            </div>
          </div>
        {% else %}
          <div class="control-group">
            <label class="control-label">{{ field.label }}</label>
            <div class="controls">{{ field }}</div>
          </div>
        {% endif %}
      {% endfor %}
    </fieldset>


    <fieldset>
      {% for field in GuideForm %}
        {% if field.errors %}
          <div class="class-group error">
            <label class="control-lable">{{ field.label }}</label>
            <div class="controls">{{ field }}
              <span class="help-inline">
                {% for error in  field.errors %}{{ error }}{% endfor %}
              </span>
            </div>
          </div>
        {% else %}
          <div class="control-group">
            <label class="control-label">{{ field.label }}</label>
            <div class="controls">{{ field }}</div>
          </div>
        {% endif %}
      {% endfor %}
    </fieldset>

    <div class="form-actions" style="margin-top: 4px;">
      <button type="submit" class="btn btn-default">Submit</button>
    </div>

  </form>
</div>

编辑我不再收到错误消息,甲板也会被创建,但不属于它的指南。

4 个答案:

答案 0 :(得分:2)

只需改变

return render_to_response('hsguides/guide_create.html', {
    'DeckForm': DeckForm,
    'GuideForm': GuideForm,
})

return render(request,'hsguides/guide_create.html', {
    'DeckForm': DeckForm,
    'GuideForm': GuideForm,
})

答案 1 :(得分:1)

我没有检查整件事,但这个地方错了,应该是:

if request.method == "POST":
    deck = DeckForm(request.POST)
    if deck.is_valid():
        # ....

您没有将POST数据打包到表单中。

同样适用于第二种形式

答案 2 :(得分:1)

试试这个,您可能忘记通过RequestContext

from django.template import RequestContext

return render_to_response('hsguides/guide_create.html', 
                          {'DeckForm': DeckForm, 'GuideForm': GuideForm},
                          RequestContext(request))

它将csrf标记传递给模板。

答案 3 :(得分:1)

您说该指南未创建。我看到这一行new_guide = deck_form.save(commit=False) .....不应该是new_guide = guide_form.save(commit=False)吗? 不是100%,但这可能是一个错误。希望,这不仅仅是因为您重构了将其放在此处的代码。