1

我想在 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

截图

我想在添加之间保留“事件”字段

4

1 回答 1

1

如果存在会话变量,您希望覆盖表单中 Event 节点的值。类似于下面的东西,但用 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

于 2013-01-18T21:28:46.473 回答