1
我想在django admin中保留對字段(在本例中爲「Event」字段)的選擇,這樣當管理員「保存並添加另一個」時,所選值不會更改。我不確定這是否是默認的django行爲。無論哪種方式,我已經覆蓋表單做一些自定義過濾/錯誤檢查。我也不想觸摸視圖/模板。我最初的計劃是將選定的值保存到會話中,然後在表單輸入時檢索它,但我找不到將請求對象傳遞到ScoreAdmin表單的方法。在django admin中保留用戶的選擇
關於接下來要做什麼的任何建議?
我至今
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
我理解的部分。我不明白的是如何將請求對象從ScoreAdmin(擴展admin.ModelAdmin)傳遞給其關聯的表單對象ScoreForm(擴展form.ModelForm)。我試圖覆蓋get_form方法無濟於事。有什麼建議麼? –