我正在尝试做一个看似简单的事情,但无法使它正常工作。
Form类中的字段集合与ChoiceField类对象相关联。 分配给这些ChoiceField的小部件是RadioSelect。这些对象的choices属性分配了一组值文本对。 表单正确显示并已挂接到数据库,但是我无法在页面加载时默认选择第一个单选按钮。在页面加载时,未选择任何按钮。
人们似乎遇到了许多与这样的问题有关的问题,但是我读到的建议中没有一个对我有用。
在Form类中声明选择字段时尝试设置默认属性
在输入表单页面URL时触发(并处理表单提交)的视图中,存在一个IF ELSE条件,该条件检查请求是否为“ POST”(否则)。我认为问题出在其他部分。
在else条件下,我设置了声明的表单对象的初始属性(使用字典> clarified_choicefield_attribute:“ Unspecified”-我需要的第一个默认选择)。 (-6是单选按钮的值),也是整数-6本身。
尝试了其他已接受答案但不起作用的帖子。 不确定Im在这里是否准确,但有一篇文章说过有关GET请求未设置默认值的事情(类似这样)。另一篇文章说有关于此问题(或类似问题)的事情与浏览器有关。
(下面是表单类)
SubmitFeedback(forms.Form)类:
CHOICES = [(-6,'Unspecified'),(-5,'-5'),(-4,'-4'),(-3,'-3'),(-2,'-2'),
(-1,'-1'),(-0,'-0'),(1,'1'),(2,'2'),(3,'3'),(4,'4'),(5,'5')]
user_satisfaction = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)
ease_of_use = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)
Meta类:
labels = {
'user_satisfaction':'How satisfied are you with this website?',
'ease_of_use':'How easy or difficult was this site to use?',
}
def clean_user_satisfaction(self):
data = self.cleaned_data['user_satisfaction']
return data
def clean_ease_of_use(self):
data = self.cleaned_data['ease_of_use']
return data
(下面是表单处理视图:)
def handleFeedbackForm(request):
feedbackForm = SubmitFeedback()
if request.method == 'POST':
feedbackForm = SubmitFeedback(request.POST)
if feedbackForm.is_valid():
newFeedback = Feedback()
newFeedback.user_satisfaction = feedbackForm.cleaned_data['user_satisfaction']
newFeedback.ease_of_use = feedbackForm.cleaned_data['ease_of_use']
newFeedback.save()
return HttpResponseRedirect( reverse('feedback_form') )
else:
feedbackForm = SubmitFeedback( initial={
'user_satisfaction':'-6',
'ease_of_use':'Unspecified',
} )
context = {
'form' : feedbackForm,
}
return render(request,'userfeedback/feedback_form.html',context)
...
希望这是足够的代码。