如何在页面加载时设置radiobutton组的默认选择(Django窗体,ChoiceField)

2024-06-16 15:56:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一件看似简单的事情,但却无法实现

窗体类分配的ChoiceField类对象中的字段集合。 分配给这些选项字段的小部件是RadioSelect。这些对象的属性选项被分配一个值文本对列表。 表单显示正确,并连接到数据库,但我无法在页面加载时获得默认选中的第一个单选按钮。页面加载时没有选择任何按钮

有许多问题似乎是关于这样一个问题,人们有,但没有一个建议,我读了工作为我

在窗体类中声明选项字段时尝试设置默认属性

在输入表单页面url(并处理表单提交)时触发的视图中,有一个IF-ELSE条件检查请求是否为“POST”(或ELSE)。我想问题在别处

在else条件中,我设置了声明的form对象的初始属性(使用dictionary>;声明的\u choicefield \u属性:'Unspecified'-我需要的第一个默认选项)在对中,我尝试将'Unspecified'更改为“-6”(-6是单选按钮的值)以及整数-6本身

在其他已经接受答案但不起作用的帖子中尝试过。 不知道我是否在这里是准确的,但一个帖子说了一件事,关于GET请求没有设置默认值(类似的事情),另一个帖子说了一件事,关于这个问题(或类似的问题)与浏览器有关

(下面是窗体类)

类提交反馈(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)

类元:

    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(请求):

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)

希望这是足够的代码


Tags: ofselfform表单data属性use选项