Python 在 __init__ 方法中设置初始 Django 表单字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22390416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting initial Django form field value in the __init__ method
提问by Steve Sawyer
Django 1.6
姜戈 1.6
I have a working block of code in a Django form class as shown below. The data set from which I'm building the form field list can include an initial value for any of the fields, and I'm having no success in setting that initial value in the form. The if field_value:block below does indeed populate the initial form dictionary attribute, but the initial value is not being displayed. Note that (in case you are wondering) the .initialattribute does not exist until after the super()call.
我在 Django 表单类中有一个工作代码块,如下所示。我从中构建表单字段列表的数据集可以包含任何字段的初始值,但我在表单中设置该初始值没有成功。if field_value:下面的块确实填充了初始表单字典属性,但未显示初始值。请注意(如果您想知道)该.initial属性直到super()调用之后才存在。
Can this be done?
这能做到吗?
If so, what I'm not doing right to make this work?
如果是这样,我做这项工作的不正确之处是什么?
Thanks!
谢谢!
def __init__(self, *args, **kwargs):
id = kwargs.pop('values_id', 0)
super(LaunchForm, self).__init__(*args, **kwargs)
# Lotsa code here that uses the id value
# to execute a query and build the form
# fields and their attributes from the
# result set
if field_value:
self.initial[field_name] = field_value
回答by ndpu
Try this way:
试试这个方法:
super(ViagemForm, self).__init__(*args, **kwargs)
if field_value:
#self.initial[field_name] = field_value
self.fields[field_name].initial = field_value
回答by Victor Guimar?es Nunes
I had that exact same problem and I solved it doing this:
我遇到了完全相同的问题,我解决了这个问题:
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
kwargs.update(initial={
# 'field': 'value'
'km_partida': '1020'
})
super(ViagemForm, self).__init__(*args, **kwargs)
# all other stuff
回答by Ray
I had a similar problem setting the initial value for a radio button called 'needs_response' and solved it by inspecting self's attributes and referencing 'declared_fields':
我在设置名为“needs_response”的单选按钮的初始值时遇到了类似的问题,并通过检查 self 的属性并引用“declared_fields”来解决它:
# views.py
def review_feedback_or_question(request, template, *args, **kwargs):
if 'fqid' in kwargs:
fqid = kwargs['fqid']
submission = FeedbackQuestion.objects.get(pk=fqid)
form = FeedbackQuestionResponseForm(submission_type=submission.submission_type)
# other stuff
# forms.py
class FeedbackQuestionResponseForm(forms.Form):
CHOICES = (('1', 'Yes'), ('2', 'No'))
response_text = forms.CharField(
required=False,
label='',
widget=forms.Textarea(attrs={'placeholder': 'Enter response...'}))
needs_response = forms.ChoiceField(choices=CHOICES,
label='Needs response?',
widget=forms.RadioSelect())
def __init__(self, *args, **kwargs):
if 'submission_type' in kwargs:
submission_type = kwargs.pop('submission_type')
if submission_type == 'question':
self.declared_fields['needs_response'].initial = 1
else:
self.declared_fields['needs_response'].initial = 2
super(FeedbackQuestionResponseForm, self).__init__(*args, **kwargs)
回答by Julio Marins
This works:
这有效:
class BarForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['state'] = forms.ChoiceField(
required=False,
choices=Foo.ADDRESS_STATE_CHOICES,
disabled='disabled',
initial='xyz',
)
state = forms.ChoiceField(
label='State',
choices=Foo.ADDRESS_STATE_CHOICES,
initial='foo',
)
回答by Megan Word
I want to mention, although this might not solve your problem, that an 'initial' dict kwarg sent to a form appears to get preference over field['field_name'].initial.
我想提一下,尽管这可能无法解决您的问题,但发送到表单的“初始”dict kwarg 似乎比field['field_name'].initial.
class MyView(View):
form = MyForm(initial={'my_field': 'first_value'})
class MyForm(Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['my_field'].initial = 'second_value'
my_fieldrendered will have initial set to 'first_value'.
my_field渲染将初始设置为'first_value'.
Some options (among others) might be:
一些选项(除其他外)可能是:
Determine second_valuein the view before initializing the form:
second_value初始化表单前在视图中确定:
class MyView(View):
# determine second_value here
form = MyForm(initial={'my_field': 'second_value'})
replace first_valuewith second_valuein initialbefore calling super():
更换first_value用second_value在initial调用之前super():
class MyForm(Form):
def __init__(self, *args, **kwargs):
# determine second_value here
if kwargs.get('initial', None):
kwargs['initial']['my_field'] = 'second_value'
super().__init__(*args, **kwargs)
Make sure 'first_value'isn't in kwargs['initial']before calling super():
在调用之前确保'first_value'不在:kwargs['initial']super()
class MyForm(Form):
def __init__(self, *args, **kwargs):
if kwargs.get('initial', None):
if kwargs['initial']['my_field']
del(kwargs['initial']['my_field']
super().__init__(*args, **kwargs)
# determine second_value here
self.fields['my_field'].initial = 'second_value'
回答by Hehe
Make initial= ""in the field definition will solve your problem. Both proposed methods are correct you need just to define initial= ""in the field definitoion and the problem is solved
让initial= ""在现场的定义将解决您的问题。两种建议的方法都是正确的,您只需要initial= ""在字段定义中定义即可解决问题

