Categories
Python Answers

How to add a Foreign Key Field to a ModelForm in Python Django?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *