2016-02-01 39 views
0

我有一些形式modelformset_factory與模型包含ForeignKey,但我需要顯示這個ForeignKey(ModelChoiceField)像CharField。我需要顯示ModelChoiceField像CharField

我用這樣的:

class SingleNeedFormWithDescription(ModelForm): 
    helper = StandardFormHelper() 
    helper.template = 'template.html' 
    need = CharField() 

    class Meta: 
     model = NeedMembershipOrganization 
     fields = ['need', 'description'] 

我有需要的ID在我的模板,但我需要need.titleneed.__str__()

我的模型:

class NeedMembershipOrganization(Model): 
    need = ForeignKey('needs.Need') 
    organization = ForeignKey(Organization) 
    description = TextField(blank=True, null=True, verbose_name='description') 

謝謝!

+0

但你打算如何使用它呢?外鍵會以對象列表的形式呈現爲下拉列表,但如果您用charfield覆蓋它,那麼您在文本框中放置了什麼? –

+0

您可以使用'autocomplete-light'自動完成文本輸入框。當相關模型有大量條目可供選擇時非常有用。 https://github.com/yourlabs/django-autocomplete-light –

+0

請參閱[本答案](http://stackoverflow.com/a/22250192/1418794)瞭解如何覆蓋默認模型表單域。 – doru

回答

2

您可以將ModelChoiceField小部件更改爲TextInput,但您可能需要找出一些方法來驗證和解析輸入。

class SingleNeedFormWithDescription(ModelForm): 

    need = forms.ModelChoiceField(
     queryset=Need.objects.all(), 
     widget=forms.TextInput)