0

I have some form modelformset_factory with model contains ForeignKey, but I need display this ForeignKey(ModelChoiceField) like CharField.

I use like that:

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

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

I have id of need in my template, but I need need.title or need.__str__().

My model:

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

Thanks!

Honnisha
  • 53
  • 7
  • But how are you going to use it then? Foreign key would be rendered as a list of objects as dropdown, but if you override it with charfield, what do you put in the text box? – Shang Wang Feb 01 '16 at 16:43
  • You can get text input formfield with autocompletion by using `autocomplete-light`. Very useful when the related model has a large number of entries to choose from. https://github.com/yourlabs/django-autocomplete-light – Håken Lid Feb 01 '16 at 16:55
  • See [this answer](http://stackoverflow.com/a/22250192/1418794) on how to override default model form fields. – doru Feb 01 '16 at 19:08

1 Answers1

3

You can change the ModelChoiceField widget to a TextInput, but you might have to figure out some way to validate and parse the input.

class SingleNeedFormWithDescription(ModelForm):

    need = forms.ModelChoiceField(
        queryset=Need.objects.all(), 
        widget=forms.TextInput)
Håken Lid
  • 22,318
  • 9
  • 52
  • 67