所以我有一个问题。我有一个模型表单:
class TeamForm(forms.ModelForm):
class Meta:
model = Team
fields = ['name','category','association','division','gender','logo','season']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(TeamForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
utils = CPUtils()
season_utils = SeasonUtils()
if instance and instance.pk is None:
self.fields['division'].initial = 1
self.fields['season'].initial = season_utils.getCurrentSeason().id
if user_role != 'admin':
self.fields['division'].widget.attrs['disabled'] = True
self.fields['division'].required = False
self.fields['season'].widget.attrs['disabled'] = True
self.fields['season'].required = False
所以我正在为场地赛季设定表格的首字母。 在我的表格上,它显示得很好。
所以现在在我的干净方法中,我想运行一些验证,我需要获得实例季节。
用我干净的方法:
if cleaned_data.get('season') is None:
cleaned_data['season'] = self.instance.season
但它说self.instance.season:DoesNotExist:团队没有季节。
我一直试图弄清楚这一段时间,我不知道发生了什么......
编辑: 这是我的模特:
name = models.CharField(max_length=25,verbose_name=_("name"))
slug = AutoSlugField(unique=True,populate_from='name')
season = models.ForeignKey(Season,verbose_name=_("season"),blank=False)
association = models.ForeignKey(Association,blank=False,null=True,verbose_name=_("association"),on_delete=models.SET_NULL)
category = models.ForeignKey(Category,verbose_name=_("category"),blank=False,null=True,default=1,on_delete=models.SET_NULL)
division = models.ForeignKey(Division,verbose_name=_("division"),blank=False,null=True,default=1,on_delete=models.SET_NULL)
此外,该实例仅在创建期间没有季节,而不是在更新期间......
谢谢, ARA
答案 0 :(得分:1)
它说的原因:
self.instance.season:DoesNotExist
您是否正在访问self
。 Self
这里实际上是表单,您要求表单查找名为instance
的属性,然后询问instance
属性,如果它具有season
属性。表单没有此属性。
您真正想要做的是根据季节ID获取Model实例,而不是Form实例。在您使用模型将数据保存到数据库之前,Form实例仅在您清理数据时暂时保存数据。
如果您尝试clean()
本赛季,那么如果您的表单中Season
为ID
,则您希望以这种方式访问它:
class TeamForm(forms.ModelForm):
# form logic here
def clean(self):
cleaned_data = super(TeamForm, self).clean()
# now get the Season Object from the cleaned_data dictionary
# if 'season' == season_id
try:
season_id = cleaned_data['season']
season = Season.object.get(pk=season_id)
except KeyError:
# season id does not exist, so do something here
pass