【问题标题】:Django 1.11 many to many does not appear in django adminDjango 1.11 多对多没有出现在 django admin 中
【发布时间】:2018-07-30 17:14:00
【问题描述】:

您好,我有一个用于通知的 django 模型,它具有多对多关系,但 django admin 中没有出现任何内容(所有字段都没有出现)

class Notification(models.Model):
    """send notification model"""

    title = models.CharField(max_length=200)
    text = models.TextField(null=True, blank=True)
    device = models.ManyToManyField(Device, null=True, blank=True)
    country = models.ManyToManyField(Country, null=True, blank=True)
    sent = models.BooleanField(default=False)

when i open django admin for this model and press add notification this is what happens (nothing appears)

国家和设备代码

class Device(models.Model):
    """Store device related to :model:`accounts.User`."""

    user = models.OneToOneField(User, related_name='device', on_delete=models.CASCADE)
    model = models.CharField(max_length=200, blank=True, null=True)
    player_id = models.CharField(max_length=200, blank=True, null=True)

    class Meta:
        verbose_name = 'Device'
        verbose_name_plural = 'Devices'

    def __str__(self):
        return self.model


class Country(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

Admin.py

from django.contrib import admin

from .models import  Notification

admin.site.register(Notification)

编辑: 谢谢 问题都解决了 问题是由设备模型中的某些条目在模型字段中确实没有任何条目引起的,因此无法正确显示它。

【问题讨论】:

  • 您能添加设备和国家/地区模型的代码吗?
  • 显示你的 admin.py 文件。

标签: django python-3.x


【解决方案1】:

根据https://code.djangoproject.com/ticket/2169

当一个类的字段没有显示在管理界面中,但 不能为空,不能添加新的。你得到一个神秘的 “请更正下面的错误。”没有显示错误的消息。这 错误消息可能应该说明隐藏字段。

现在 ManyToManyFields 不需要 null=True,请尝试删除这些语句,看看是否有改进。

另外,尝试在 admin.py 中添加 Country 和 Device 模型,以便管理员可以看到并显示它们。

【讨论】:

  • 感谢您的帮助,我尝试了您的解决方案,但没有任何改变
  • 如果将 Country 和 Device 添加到 admin.py 会怎样?由于您有一个多对多,添加这些模型管理员可能需要访问这些模型
【解决方案2】:

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#working-with-many-to-many-models

在 admin.py 中为多对多定义一个内联:

from django.contrib import admin

class DeviceInline(admin.TabularInline):
    model = Notification.device.through

class CountryInline(admin.TabularInline):
    model = Notification.country.through

class NotificationAdmin(admin.ModelAdmin):
    inlines = [
        DeviceInline, CountryInline
    ]
    exclude = ("device", "country")

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 2011-02-28
    • 2015-11-08
    • 2016-02-23
    • 1970-01-01
    • 2010-11-16
    • 2018-03-04
    • 2017-10-11
    • 2012-10-20
    相关资源
    最近更新 更多