如何在管理界面[Django]中添加内联模型

时间:2018-05-06 17:36:21

标签: python django python-2.7

我正在尝试将内联模型添加到Post模型中。正如docs所说,我正在尝试做类似的事情:

models.py

from django.db import models

class images(models.Model):
    image = models.ImageField(upload_to='images/')

class Post(models.Model):
    Title = models.CharField(max_length=60)
    Images = models.ForeignKey(images)

admin.py

from django.contrib import admin
from . import models

class ModelInlinePost(admin.TabularInline):
    model = models.images

class ModelPost(admin.ModelAdmin):
    view_on_site = False
    inlines = [PythonInlineAdmin,]

当我尝试使用manage.py执行任何命令时。它抛出了这个错误:

python manage.py makemigrations
SystemCheckError: System check identified some issues:

ERRORS:
 <class 'home.admin.ModelInlinePost'>: (admin.E202) 'home.Post' has no ForeignKey to 'home.images'.

1 个答案:

答案 0 :(得分:0)

尝试删除所有没有图片的帖子。以下代码适用于我: -

模型

class Image(models.Model):
  image = models.ImageField(upload_to='images/')

class Post(models.Model):
  image = models.ForeignKey(Image, on_delete=models.CASCADE)
  title = models.CharField(max_length=50)

管理

class ImageInline(admin.TabularInline):
    model = Image

class PostAdmin(admin.ModelAdmin):
    inlines = [
        ImageInline,
    ]