iamageek
iamageek

Reputation: 3

How to show ForeignKey fields in Model Form

# models.py

class modelA(models.Model):
    a = models.CharField()
    b = models.CharField()

class ModelB(models.Model):
    c = models.CharField()
    d = models.ForeignKey(modelA)

# forms.py

class myForm (ModelForm):
    class Meta: 
       model = ModelB
       fields = ('d')
       widgets = { 'd' : TextInput() }

I want to show a form which displays a and b fields as TextInputand how to do it?

The above forms.py code displays d as name but not its fields..

Upvotes: 0

Views: 1857

Answers (1)

dani herrera
dani herrera

Reputation: 51645

It seems you are looking for inline formsets:

Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key. Suppose you have these two models ...

For your models:

from django.forms.models import inlineformset_factory
ModelBFormSet = inlineformset_factory(ModelB, ModelA)
BInstance = ModelB.objects.get(a=u'some value')
formset = ModelBFormSet(instance=BInstance)

Read "Using an inline formset in a view" to learn how to use factory.

Upvotes: 2

Related Questions