我在使用Django表单和ModelForm类的非常时髦的属性时遇到了困难。特别是,当表单实例与模型实例实例化时,我很难确定表单实例是否有关联的数据。
首先,我们来看看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中得到了期望
发布于 2017-03-08 22:26:17
但你还没有把它绑定到数据上。您提供了一个实例参数,但这完全不是一回事;这只是将表单与提供初始值和保存更新的模型实例关联起来。绑定与未绑定取决于您是否传递任何数据,通常来自POST。
如果您想根据是否存在实例更改按钮,那么只需这样做:
{% if form.instance %}
<button type="submit" name="button">Update</button>
{% else %}
<button class="btn btn-lg btn-primary" type="submit" name="button">Add</button>
{% endif %}https://stackoverflow.com/questions/42683031
复制相似问题