我有两个模型,都有字段“状态”,对它们有不同的含义.
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获取值不正确.我需要解决这个问题,而不更改模型字段的名称,但不知道如何.