django在一个模板上具有相同字段名称的两个ModelForms

时间:2015-10-05 10:45:15

标签: python django django-models django-forms django-templates

我有两个型号,都有现场状态'这对他们来说意义不一。

class Order(models.Model):
    ...
    status = models.PositiveIntegerField(default=0, choices=ORDER_STATUSES)
    ...

class ACS(models.Model):
    status = models.IntegerField(default=-1, choices=STATUSES)
    order = models.ForeignKey(Order, blank=True, null=True)
    ...

他们的表格如下:

class ACSForm(forms.ModelForm):
    status = forms.ChoiceField(
        choices=STATUSES,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    ...

    class Meta:
       model = ACS
       fields = ('status',)

class OrderACSEditForm(forms.ModelForm):
    status = forms.ChoiceField(
        choices=ORDER_STATUSES,
        widget=forms.Select(attrs={'class': 'form-control'})
    )

    class Meta:
        model = Order
        fields = ('status',)

我想在同一页面上编辑这两个字段。我的 view.py 看起来像

def edit(request, item_id=""):
    data = ACS.objects.get(pk=item_id)
    form = ACSForm(instance=data)
    order = Order.objects.get(id=data.order.id)
    form_edit = OrderACSEditForm(instance=order)
    if request.POST:
        form = ACSForm(request.POST, instance=data)
        form_edit = OrderACSEditForm(request.POST)
        if form.is_valid() and form_edit.is_valid():
            form_edit.save()
            obj = form.save()
            messages.add_message(request, messages.SUCCESS, 'Your data successfully saved.')

        if request.POST['action'] == "save_stay":
            return redirect("/panel/packages/acs/edit/" + str(obj.id))
        else:
            return redirect("/panel/packages/acs/")
    return render(request, 'ui/packages/acs/edit.html', dict(data=data, form=form, form_edit=form_edit, item_id=item_id))

模板

<div class="form-group {% if form.status.errors %}has-error{% endif %}">
    <label>{% trans "Status" %}</label>
        {% if form.status.errors %}
            {% for error in form.status.errors %}
                <label class="control-label">{{ error }}</label>
            {% endfor %}
        {% endif %}
        {{ form.status }}
</div>

<div class="form-group {% if form_edit.status.errors %}has-error{% endif %}">
    <label>{% trans "Order status" %}</label>
        {% if form_edit.status.errors %}
            {% for error in form_edit.status.errors %}
                <label class="control-label">{{ error }}</label>
            {% endfor %}
        {% endif %}
        {{ form_edit.status }}
</div>

但是在结果form.status中从form_edit.status获取值不正确。我需要在不更改模型字段名称的情况下解决此问题,但不知道如何。

1 个答案:

答案 0 :(得分:7)

使用表单的prefix参数来命名字段名称。

form = ACSForm(prefix='acs', instance=data)
form_edit = OrderACSEditForm(prefix='edit', instance=order)

在使用POST数据实例化表单时,请记住使用相同的前缀。