我想在 django 管理员中保留一个字段(在本例中为“事件”字段)的选择,这样当管理员“保存并添加另一个”时,所选值不会改变。我不确定这是否是默认的 django 行为。无论哪种方式,我都可以覆盖表单来进行一些自定义过滤/错误检查。我也不想触摸视图/模板。我最初的计划是将选定的值保存到会话中,然后在表单初始化时检索它,但我找不到将请求对象传递到 ScoreAdmin 表单的方法。
关于下一步做什么的任何建议?
到目前为止我所拥有的
class ScoreForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ScoreForm, self).__init__(*args, **kwargs)
self.request = kwargs.pop('request', None)
standard_events = Event.objects.filter(event_score_type='STD')
event_widget = self.fields['event'].widget
choices = []
for element in standard_events:
choices.append((element.id, element.name))
event_widget.choices = choices
def clean_score(self):
print self.request.session
print(self.cleaned_data['event'])
selected_event = Event.objects.get(name=self.cleaned_data['event'])
if(selected_event.max_score > selected_event.min_score):
if self.cleaned_data['score'] < 0:
raise forms.ValidationError("Score Cannot Be Negative")
elif self.cleaned_data['score'] > selected_event.max_score:
raise forms.ValidationError("Score Cannot Be Greater Than Best Possible Score of " + str(selected_event.max_score))
elif self.cleaned_data['score'] < selected_event.min_score:
raise forms.ValidationError("Score Cannot Be Less Than Worst Possible Score of " + str(selected_event.min_score))
else:
return self.cleaned_data['score']
elif selected_event.max_score < selected_event.min_score:
if self.cleaned_data['score'] < 0:
raise forms.ValidationError("Score Cannot Be Negative")
elif self.cleaned_data['score'] < selected_event.max_score:
raise forms.ValidationError("Score Cannot Be Less Than Best Possible Score of " + str(selected_event.max_score))
elif self.cleaned_data['score'] > selected_event.min_score:
raise forms.ValidationError("Score Cannot Be Greater Than Worst Possible Score of " + str(selected_event.min_score))
else:
return self.cleaned_data['score']
class Meta:
model = Score
class ScoreAdmin(admin.ModelAdmin):
form = ScoreForm
pass
截图