当前位置: 动力学知识库 > 问答 > 编程问答 >

python - modifying django modelform select set

问题描述:

I created model with choices option:

SERVICE_CHOICES = (

('Apps', 'Apps'),

('Ask', 'Ask'),

('Auth', 'Auth')

class InputsModelExtended(models.Model):

service = models.CharField(max_length=1000, choices=SERVICE_CHOICES, blank=True)

And then created model form from it:

class InputsModelExtendedForm(ModelForm):

class Meta:

model = InputsModelExtended

widgets = {'service': forms.fields.Select(attrs={'class': 'my_select_boxx'})}

I pass this form to template from views.py:

def input_form(request):

form = InputsModelExtendedForm

return render(request, 'inputs_forms_css.html', {'form': form})

Can 'service' select choice set be modified directly from views.py? Thx.

网友答案:

Sure. Just pass the choices tuple as a parameter to your form class when you instantiate it:

# some code left out for brevity

class InputsModelExtendedForm(ModelForm):
    class Meta:
        model = InputsModelExtended

    def __init__(self, *args, **kwargs):
        service_choices = kwargs.pop('service_choices')
        super(InputsModelExtendedForm, self).__init__(*args, **kwargs)

        if service_choices:
            self.fields['service'] = forms.ChoiceField(choices=service_choices,
                                                       required=False)

# example usage:

def my_view(request):
    service_choices = (
        ('Foo', 'Foo',),
        ('Bar', 'Bar',),
        ('Baz', 'Baz',),
    )

    form = InputsModelExtendedForm(request.POST or None, service_choices=service_choices)

This way you get the defaults you set on the model, or you can override it from the view.

分享给朋友:
您可能感兴趣的文章:
随机阅读: