我有以下表格:
class PlayerAchievementForm(forms.ModelForm):
class Meta:
model = PlayerAchievement
fields = ('achievement',)
def __init__(self, *args, **kwargs):
super(PlayerAchievementForm, self).__init__(**kwargs)
self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)
我在视图中有以下实现:
def points(request, action, target=None):
if request.method == 'POST':
if target == 'player':
form = PlayerAchievementForm(request.POST)
print form.errors
if form.is_valid():
print 'valid'
elif:
print 'invalid'
在提交时,这会打印无效。
如果我在表格中取出这一行:
def __init__(self, *args, **kwargs):
super(PlayerAchievementForm, self).__init__(**kwargs)
self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)
然后它保存没有问题。 init有什么问题?
答案 0 :(得分:1)
我在这里找到答案:DJango form with custom __init__ not validating
我失踪了:
super(PlayerAchievementForm, self).__init__(*args, **kwargs)
答案 1 :(得分:0)
我遇到了同样的问题,经过多次尝试,对我有用的代码是这样的:
(请注意该字段在类级别的第一个实例化。)
class PlayerAchievementForm(forms.ModelForm):
achievement = Achievement.objects.filter(input_type=0)
class Meta:
model = PlayerAchievement
fields = ('achievement',)
def __init__(self, *args, **kwargs):
super(PlayerAchievementForm, self).__init__(**kwargs)
self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)