开发者

Set custom 'name' attribute for RadioSelect in Django

开发者 https://www.devze.com 2023-01-09 06:48 出处:网络
I\'m trying to set custom \'name\' attribute in django form. I\'ve been trying this kind of approach: class BaseQuestionForm(forms.Form):

I'm trying to set custom 'name' attribute in django form.

I've been trying this kind of approach:

class BaseQuestionForm(forms.Form):
  question_id = forms.CharField(widget=forms.HiddenInput)
  answer = forms.ChoiceField(choices = [ ... ], widget=forms.RadioSelect)

and then setting the 'name'-attr on answer with:

form.fields['answer'].widget.name = 'new_name'

But this does not work, and name is always开发者_JAVA百科 set to 'answer' as in field name. Is there some way to do this?


First try:

print form.fields['answer'].widget.name

I believe widget doesn't have a name (ok, I am even pretty sure ;-)).

To achieve what you want, you would have to:

form.fields['new_name'] = form.fields['answer']
del form.fields['answer']

This however will move new_name field to the bottom of fields if you use simply {{ form }} in the template (this dictionary is ordered). Django builds the form fields names in template using names of the keys.

0

精彩评论

暂无评论...
验证码 换一张
取 消