我在使用Django窗體和ModelForm類的公然相當時髦的屬性時遇到了困難。特別是我無法確定一個表單實例是否有與模型實例實例化相關聯的數據。即使使用模型實例實例化Django窗體顯示爲未綁定
先到這裏來看看一個非常簡單的一套形式forms.py
from django.forms import ModelForm
from .models import ItemCoeff, MonthCoeff
class MonthForm(ModelForm):
"""A class that defines an HTML form that will be constructed for interfacing with the Monthly Coefficients"""
title='Set Month Coefficient'
class Meta:
model=MonthCoeff
fields = ['first_of_month', 'product_category', 'month_coeff', 'notes']
class ItemForm(ModelForm):
"""
A class that defines a Django HTML form to be constructed for interfacing with the ItemCoeff model.
"""
title='Set Item Coefficient'
class Meta:
model=ItemCoeff
fields = ['item_num','item_name','item_coeff','notes']
接下來,我們到了views.py
的一部分,我用表格
def set_month_form(request, myid=False):
if myid:
mcoeff=MonthCoeff.objects.get(id=myid)
form=MonthForm(instance = mcoeff)
categories = False
else:
form=MonthForm()
categories=list(MonthCoeff.objects.values('product_category').distinct())
import pdb; pdb.set_trace()
return render(request,'coeffs/forms/django_form.html',{'form':form, 'user': request.user})
,當我渲染窗體在我的模板我試圖使用is_bound屬性來設置我的提交按鈕的標題,如下所示:
{% if form.is_bound %}
<button type="submit" name="button">Update</button>
{% else %}
<button class="btn btn-lg btn-primary" type="submit" name="button">Add</button>
{% endif %}
但是,此方法始終會產生else
條件。我確定你注意到了,我在我的view.py
代碼中設置了一個pdb跟蹤,並且在渲染form.is_bound
時返回False
時檢查表單對象。即使form['first_of_month']
返回與用於創建表單的MonthCoeff實例關聯的值,也會發生這種情況。
有沒有人有任何見解,爲什麼is_bound屬性沒有響應,因爲我已經導致期望從其他精彩Django Docs?
謝謝,這就像一個魅力。我無法分離出「綁定」與「實例」。我忘了你可以在Python中評估諸如實例的布爾值屬性。太多時間在蹩腳的語言中工作。 – RyanM