Django:如何基于以前的ChoiceField更新IntegerField,但是保持它可编辑?

时间:2018-04-23 15:37:10

标签: python django web django-models django-forms

我有以下形式:

new File

我想根据dificulty字段选择更改xp字段。

就像,如果用户将EASY设置为dificulty,请将xp更改为30.但是保持其可编辑状态,以便用户可以指定它是31还是29,或类似的东西。

1 个答案:

答案 0 :(得分:0)

表单的clean方法在这里会派上用场

class form1(forms.ModelForm):
    DEFAULT_XP_MAP = ('EASY': 30, 'MEDIUM': ...)
    CHOICES = (('EASY', 'EASY'), ('MEDIUM', 'MEDIUM'), ('HARD', 'HARD'))
    dificulty = forms.ChoiceField(choices=CHOICES)
    xp = forms.IntegerField()

    def _get_default_xp(difficulty):
        return self.DEFAULT_XP_MAP.get(difficulty, None)

    def clean():
        cleaned_data = super(form1, self).clean()
        difficulty = cleaned_data.get('difficulty')
        xp = cleaned_data.get('xp')
        if difficulty and not xp:  # Set defaults
            cleaned_data['xp'] = self._get_default_xp(difficulty)
        return cleaned_data

要使用jQuery在FE上实现相同的功能,您可以这样做:

(function () {
  $ = window.jQuery;
  $(document).ready(function () {
    var default_xp_map = {
        'EASY': 30,
        'MEDIUM': 60, 
        'HARD': 90,
    };
    var $difficulty = $("#difficulty");  // Difficulty form input field
    var $xp = $('#xp');  // XP form input field
    $difficulty.on('blur', function() {
        if ($difficulty.val() && !$xp.val()) {  // Difficulty is set; but xp is not set 
            $xp.val(default_xp_map[$difficulty.val()]);
        }
    });
  });
})();