Sometimes, we want to add a Foreign Key Field to a ModelForm in Python Django.
In this article, we’ll look at how to add a Foreign Key Field to a ModelForm in Python Django.
How to add a Foreign Key Field to a ModelForm in Python Django?
To add a Foreign Key Field to a ModelForm in Python Django, we can add the field to the self.fields
dict.
For instance, we write
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
def __init__(self, *args, **kwargs):
user = kwargs.pop('user','')
super(DocumentForm, self).__init__(*args, **kwargs)
self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
to add the user_defined_code
field by writing
self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
We get the choices for the field by setting the queryset
argument to UserDefinedCode.objects.filter(owner=user)
.
Conclusion
To add a Foreign Key Field to a ModelForm in Python Django, we can add the field to the self.fields
dict.