在__init__方法中设置初始Django表单字段值

时间:2014-03-13 20:40:35

标签: python django django-1.6

Django 1.6

我在Django表单类中有一个工作代码块,如下所示。我正在构建表单字段列表的数据集可以包含任何字段的初始值,而我在表单中设置该初始值时没有成功。下面的if field_value:块确实填充了初始表单字典属性,但未显示初始值。请注意(如果您想知道).initial属性在super()调用之后才会存在。

可以这样做吗?

如果是这样的话,我做这项工作的做法是不正确的?

谢谢!

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

6 个答案:

答案 0 :(得分:28)

我遇到了同样的问题,我解决了这个问题:

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

答案 1 :(得分:21)

尝试这种方式:

super(ViagemForm, self).__init__(*args, **kwargs)

if field_value:
    #self.initial[field_name] = field_value
    self.fields[field_name].initial = field_value

答案 2 :(得分:4)

我想提一下,虽然这可能无法解决您的问题,但最初的' 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_field初始设置为'first_value'

某些选项(以及其他选项)可能是:

在初始化表单之前确定视图中的second_value

class MyView(View):
    # determine second_value here
    form = MyForm(initial={'my_field': 'second_value'})
在调用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)

在致电'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'

答案 3 :(得分:0)

我有一个类似的问题,设置名为'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)

答案 4 :(得分:0)

这有效:

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',
    )

答案 5 :(得分:0)

在字段定义中输入initial= ""将解决您的问题。两种建议的方法都是正确的,您只需要在字段定义中定义initial= ""即可解决问题