반응형
Django admin ManyToMany inline “has no ForeignKey to” error
I'm setting up the Django admin to the following models:
class Quote(models.Model):
author = models.CharField(max_length=100)
quote = models.CharField(max_length=1000)
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = models.CharField(max_length=100)
With the following code:
class TagInline(admin.TabularInline):
model = Tag
class QuoteAdmin(admin.ModelAdmin):
list_display = ('author', 'quote')
inlines = (TagInline,)
class TagAdmin(admin.ModelAdmin):
pass
admin.site.register(Quote, QuoteAdmin)
admin.site.register(Tag, TagAdmin)
When trying to view the admin page to add a Quote, the page shows an error saying <class 'quotes.models.Tag'> has no ForeignKey to <class 'quotes.models.Quote'>. This didn't happen before I added an inline. What's the problem? How do I correctly add a Tag as an inline?
(I spent a good 20 minutes searching for an answer; I found similar questions but none of their answers worked for me.)
Admin documentation has a section dedicated to inlining with many-to-many relationships. You should use Quote.tags.through as a model for TagInline, instead of Tag itself.
반응형
'Program Club' 카테고리의 다른 글
| ConfigurationManager.AppSettings-수정 및 저장 방법 (0) | 2020.10.22 |
|---|---|
| How to set main class in build? (0) | 2020.10.21 |
| How to create websockets server in PHP (0) | 2020.10.21 |
| How to fix Android Studio getting stuck executing Gradle tasks? (0) | 2020.10.21 |
| Haskell “do nothing” IO, or if without else (0) | 2020.10.21 |