2015-05-28 77 views
0

我創建了選擇期權模型:修改的Django的ModelForm選擇設置

SERVICE_CHOICES = (
    ('Apps', 'Apps'), 
    ('Ask', 'Ask'), 
    ('Auth', 'Auth') 

class InputsModelExtended(models.Model): 
    service = models.CharField(max_length=1000, choices=SERVICE_CHOICES, blank=True) 

然後創建模型的形式從中:

class InputsModelExtendedForm(ModelForm): 
    class Meta: 
     model = InputsModelExtended 
     widgets = {'service': forms.fields.Select(attrs={'class': 'my_select_boxx'})} 

我通過這種形式,以模板從views.py:

def input_form(request): 
    form = InputsModelExtendedForm 
    return render(request, 'inputs_forms_css.html', {'form': form}) 

'service'select choice set可以直接從views.py中修改嗎?謝謝。

+0

將這些選項放在某個Service模型中,並將服務的FK字段設置爲這個模型的FK不是更好的解決方案嗎? –

回答

0

當然。只需通過選擇元組作爲參數傳遞給你的窗體類當實例吧:

# 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) 

這樣你得到你的模型設置的默認值,也可以從該視圖覆蓋它。

+0

爲我工作,謝謝! –

+0

不客氣。總是樂於提供幫助。 – Brandon