在django admin中保留用户的选择

时间:2013-01-18 05:11:34

标签: python django django-forms django-admin

我想在django admin中坚持选择一个字段(在本例中为“Event”字段),这样当管理员“保存并添加另一个”时,所选的值不会改变。我不确定这是否是默认的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

截图

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

1 个答案:

答案 0 :(得分: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