简体   繁体   English

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

[英]Setting initial Django form field value in the __init__ method

Django 1.6姜戈 1.6

I have a working block of code in a Django form class as shown below.我在 Django 表单类中有一个工作代码块,如下所示。 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.下面的if field_value:块确实填充了初始表单字典属性,但未显示初始值。 Note that (in case you are wondering) the .initial attribute does not exist until after the super() call.请注意(如果您想知道的话) .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

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

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

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_field rendered will have initial set to 'first_value' .呈现的my_field将初始设置为'first_value'

Some options (among others) might be:一些选项(除其他外)可能是:

Determine second_value in the view before initializing the form:在初始化表单之前确定second_value中的second_value

class MyView(View):
    # determine second_value here
    form = MyForm(initial={'my_field': 'second_value'})

replace first_value with second_value in initial before calling super() :在调用super()之前将first_value替换为second_valueinitial

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() :在调用super()之前确保'first_value'不在kwargs['initial']

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'

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)

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

Make initial= "" in the field definition will solve your problem.在字段定义中使用initial= ""将解决您的问题。 Both proposed methods are correct you need just to define initial= "" in the field definitoion and the problem is solved两种建议的方法都是正确的,您只需要在字段定义中定义initial= ""解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM