2013-01-18 43 views
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 

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

回答

1

要改寫形式事件節點的值,如果有一個存在的會話變量的屏幕截圖。像下面的東西,但包裹了一個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

+0

我理解的部分。我不明白的是如何將請求對象從ScoreAdmin(擴展admin.ModelAdmin)傳遞給其關聯的表單對象ScoreForm(擴展form.ModelForm)。我試圖覆蓋get_form方法無濟於事。有什麼建議麼? –