gpt4 book ai didi

python - 在 django admin 中保留用户的选择

转载 作者:太空宇宙 更新时间:2023-11-03 19:07:13 24 4
gpt4 key购买 nike

我想在 django 管理中保留一个字段(在本例中为“事件”字段)的选择,这样当管理员“保存并添加另一个”时,所选值不会更改。我不确定这是否是 django 的默认行为。无论哪种方式,我都覆盖了表单来进行一些自定义过滤/错误检查。我也不想接触 View /模板。我最初的计划是将所选值保存到 session 中,然后在表单初始化时检索它,但我找不到将请求对象传递到 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

截图

I want to persist the 'Event' field in between additions

最佳答案

如果存在 session 变量,您希望覆盖表单中事件节点的值。类似于下面的内容,但用 if 包裹起来。如果没有型号信息,很难获得太具体的信息,但这应该可以让您有一个大概的了解。

class ScoreForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ScoreForm, self).__init__(*args, **kwargs) # call the parent init
self.initial['Event'] = self.get_my_session_var

主要来自这篇文章中的信息: How to override field value display in Django admin change form

关于python - 在 django admin 中保留用户的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com