How to include editable ForeignKey in Django Admin?

Published 23 Jan, 2023

Reading time: 1 Mins


To include the Foreign Key in Django Admin panel you can use inlines variable in admin class

There is a way to include editable ForeignKey in the Django Admin panel. All you need to do is to incorporate Tabular or Stacked Inline classes. Take a look at this example we have skills and related skills in the separate model.

class Skill(models.Model):
	name = models.CharField(max_length=200, null=True, blank=True)

class RelatedSkill(models.Model):
	skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
  name = models.CharField(max_length=200, null=True, blank=True)```
If we define the ModelAdmin either you defined it in the separate entry right? But what if you want to create or edit the added related skill in the admin Skills objects page itself?  
That can be achieved by the StackedInline or TabularInline. Oh I personally like the StackedInline.
```python
class RelatedSkillInline(models.StackedInline):
	model = RelatedSkill

class SkillAdmin(models.ModelAdmin):
	inlines = [RelatedSkillInline]

admin.site.register(Skill, SkillAdmin)```

Read More