Python Django将禁用的表单作为默认选中表单
我目前有以下代码。在我的表格里Python Django将禁用的表单作为默认选中表单,python,html,django,django-forms,django-templates,Python,Html,Django,Django Forms,Django Templates,我目前有以下代码。在我的表格里 from django import forms from django.forms.widgets import Select class SelectWithDisabled(Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): disabled = False if isin
from django import forms
from django.forms.widgets import Select
class SelectWithDisabled(Select):
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
disabled = False
if isinstance(label, dict):
label, disabled = label['label'], label['disabled']
option_dict = super(SelectWithDisabled, self).create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs)
if disabled:
option_dict['attrs']['disabled'] = 'disabled'
return option_dict
GAME_PHASES = [
('default', {'label': 'Choose an option', 'disabled': True}),
('opening', 'Opening'),
('midgame', 'Midgame'),
('endgame', 'Endgame'),
]
class SettingsForm(forms.Form):
game_phases = forms.ChoiceField(label='Phase of the Game:', choices=GAME_PHASES, required=True, widget=SelectWithDisabled)
为了在纯HTML代码中进行澄清,我希望我的代码执行以下操作:
<label for="phase">Phase of the Game:</label><br>
<select name="phase" id="phase" required>
<option selected disabled>Choose an option</option>
<option value="opening">Opening</option>
<option value="midgame">Midgame</option>
<option value="endgame">Endgame</option>
</select>
另外:我刚刚想到重写views.py文件中的form.is\u valid()方法,然后不禁用第一个选项。我会重写它,因此如果选择“默认”值,它将被标记为无效。
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import SettingsForm
def home_view(request):
if request.method == 'GET':
form = SettingsForm(request.GET)
if form.is_valid():
return HttpResponseRedirect('/play')
else:
form = SettingsForm()
return render(request, "home.html", {
'form': form
})