根据用户选择动态更改ModelChoiceField初始值

时间:2019-10-15 15:11:38

标签: python django django-forms django-templates django-views

我有三个ModelChoiceFields。用户在第一个复选框(级别)中设置了值之后,其他两个复选框的初始值应更改。

Views.py

def index(request):
    form = SettingsForm()

    context = {
        'form' : form
    }

    return render(request, 'app/settings.html', context)

settings.html

  <form method="post">
    {% csrf_token %}
    <table>
      {{ settings_form }}
    </table>
    <button type="submit" class="button">Apply</button>
  </form>

forms.py

class SettingsForm(forms.ModelForm):
    class Meta:
        model = Setting
        fields = '__all__'

    level = forms.ModelChoiceField(
        widget = forms.Select,
        queryset = Level.objects.all()
    )

    language = forms.ModelChoiceField(
        widget = forms.Select,
        queryset = Language.objects.all(),
        initial = 0
    )

    country = forms.ModelChoiceField(
        widget = forms.Select,
        queryset = Country.objects.all()
    )

# I know I can do something like this in __init__:
# self.fields['language'].initial = Language.objects.filter(level=self.level).first()
# but that is not dynamically

示例

用户选择级别= 2,因此language.initial应该设置为“ German”,country.initial应该设置为“ Germany”。

如果用户选择级别= 1,则language.initial应该设置为“英语”,County.initial应该设置为“美国”。

你们中的一个可以指导我实现这个目标吗?

0 个答案:

没有答案