foreignKey 字段不会出现在 Django 管理站点中

发布于 2024-11-03 21:13:29 字数 2899 浏览 2 评论 0原文

模型上的外键未出现在 Django 管理站点中。这与是否在 ModelAdmin 实例中显式指定该字段无关(fields = ('title', 'field-that-does-not-show-up'))。

我意识到有很多变量可能导致这种行为。

class AdvertiserAdmin(admin.ModelAdmin):
    search_fields = ['company_name', 'website']
    list_display = ['company_name', 'website', 'user']


class AdBaseAdmin(admin.ModelAdmin):
    list_display = ['title', 'url', 'advertiser', 'since', 'updated', 'enabled']
    list_filter = ['updated', 'enabled', 'since', 'updated', 'zone']
    search_fields = ['title', 'url']

问题是广告商外键没有显示在 AdBase 的管理中

class Advertiser(models.Model):
    """ A Model for our Advertiser
    """
    company_name = models.CharField(max_length=255)
    website = models.URLField(verify_exists=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return "%s" % self.company_name

    def get_website_url(self):
        return "%s" % self.website

class AdBase(models.Model):
    """
    This is our base model, from which all ads will inherit.
    The manager methods for this model will determine which ads to
    display return etc.

    """
    title = models.CharField(max_length=255)
    url = models.URLField(verify_exists=True)
    enabled = models.BooleanField(default=False)
    since = models.DateTimeField(default=datetime.now)
    expires_on=models.DateTimeField(_('Expires on'), blank=True, null=True)
    updated = models.DateTimeField(editable=False)

    # Relations
    advertiser = models.ForeignKey(Advertiser)
    category = models.ForeignKey(AdCategory)
    zone = models.ForeignKey(AdZone)

    # Our Custom Manager
    objects = AdManager()

    def __unicode__(self):
        return "%s" % self.title

    @models.permalink
    def get_absolute_url(self):
        return ('adzone_ad_view', [self.id])

    def save(self, *args, **kwargs):
        self.updated = datetime.now()
        super(AdBase, self).save(*args, **kwargs)

    def impressions(self, start=None, end=None):
        if start is not None:
            start_q=models.Q(impression_date__gte=start)
        else:
            start_q=models.Q()
        if end is not None:
            end_q=models.Q(impression_date__lte=end)
        else:
            end_q=models.Q()
        return self.adimpression_set.filter(start_q & end_q).count()

    def clicks(self, start=None, end=None):
        if start is not None:
            start_q=models.Q(click_date__gte=start)
        else:
            start_q=models.Q()
        if end is not None:
            end_q=models.Q(click_date__lte=end)
        else:
            end_q=models.Q()
        return self.adclick_set.filter(start_q & end_q).count()

class BannerAd(AdBase):
    """ A standard banner Ad """
    content = models.ImageField(upload_to="adzone/bannerads/")

。这个谜团加深了。我只是尝试为 AdBase 和 BannerAd 创建一个 ModelForm 对象,并为广告商生成两个字段。这里发生了一些疯狂的管理事情......

A foreign key on a model is not appearing in the Django admin site. This is irrespective of whether the field is explicitly specified in a ModelAdmin instance (fields = ('title', 'field-that-does-not-show-up')) or not.

I realize there are many variables that could be causing this behavior.

class AdvertiserAdmin(admin.ModelAdmin):
    search_fields = ['company_name', 'website']
    list_display = ['company_name', 'website', 'user']


class AdBaseAdmin(admin.ModelAdmin):
    list_display = ['title', 'url', 'advertiser', 'since', 'updated', 'enabled']
    list_filter = ['updated', 'enabled', 'since', 'updated', 'zone']
    search_fields = ['title', 'url']

The problem is the advertiser foreign key is not showing up in the admin for AdBase

class Advertiser(models.Model):
    """ A Model for our Advertiser
    """
    company_name = models.CharField(max_length=255)
    website = models.URLField(verify_exists=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return "%s" % self.company_name

    def get_website_url(self):
        return "%s" % self.website

class AdBase(models.Model):
    """
    This is our base model, from which all ads will inherit.
    The manager methods for this model will determine which ads to
    display return etc.

    """
    title = models.CharField(max_length=255)
    url = models.URLField(verify_exists=True)
    enabled = models.BooleanField(default=False)
    since = models.DateTimeField(default=datetime.now)
    expires_on=models.DateTimeField(_('Expires on'), blank=True, null=True)
    updated = models.DateTimeField(editable=False)

    # Relations
    advertiser = models.ForeignKey(Advertiser)
    category = models.ForeignKey(AdCategory)
    zone = models.ForeignKey(AdZone)

    # Our Custom Manager
    objects = AdManager()

    def __unicode__(self):
        return "%s" % self.title

    @models.permalink
    def get_absolute_url(self):
        return ('adzone_ad_view', [self.id])

    def save(self, *args, **kwargs):
        self.updated = datetime.now()
        super(AdBase, self).save(*args, **kwargs)

    def impressions(self, start=None, end=None):
        if start is not None:
            start_q=models.Q(impression_date__gte=start)
        else:
            start_q=models.Q()
        if end is not None:
            end_q=models.Q(impression_date__lte=end)
        else:
            end_q=models.Q()
        return self.adimpression_set.filter(start_q & end_q).count()

    def clicks(self, start=None, end=None):
        if start is not None:
            start_q=models.Q(click_date__gte=start)
        else:
            start_q=models.Q()
        if end is not None:
            end_q=models.Q(click_date__lte=end)
        else:
            end_q=models.Q()
        return self.adclick_set.filter(start_q & end_q).count()

class BannerAd(AdBase):
    """ A standard banner Ad """
    content = models.ImageField(upload_to="adzone/bannerads/")

The mystery deepens. I just tried to create a ModelForm object for both AdBase and BannerAd, and both generated fields for the advertiser. Some crazy admin things going on here...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

一张白纸 2024-11-10 21:13:29

我相信我刚刚遇到了完全相同的问题,但由于坚持不懈的同事的帮助,我能够调试它。 :)

简而言之,如果您查看原始 HTML 源代码,您会发现该字段始终存在 - 只是这样:

  • Django 尝试变得聪明,将表单字段放入带有 CSS class="form- 的 div 中row $FIELD_NAME"
  • 字段名称为“advertiser”,因此 CSS 类为“form-rowadvertiser”,
  • ...Adblock Plus。

Adblock Plus 将隐藏 CSS 类“advertiser”的任何内容,以及大量其他 CSS 类。

我认为这是 Django 中的一个错误。

I believe I've just run into exactly the same problem, but was able to debug it thanks to the help of persistent co-workers. :)

In short, if you look in the raw HTML source you'll find the field was always there - it's just that:

  • Django tries to be clever and put the form field inside a div with CSS class="form-row $FIELD_NAME",
  • The field's name was "advertiser", so the CSS class was "form-row advertiser",
  • ...Adblock Plus.

Adblock Plus will hide anything with the CSS class "advertiser", along with a hell of a lot of other CSS classes.

I consider this a bug in Django.

叶落知秋 2024-11-10 21:13:29

也许这是一个编码错误。我遇到了同样的问题,但是当我在 models.py 中添加 # --coding: UTF-8 -- 时,一切都很好。

maybe it is an encode error. I had the same problem, but when i added # -- coding: UTF-8 -- in the models.py, all fine.

﹉夏雨初晴づ 2024-11-10 21:13:29

同一问题的另一个非常愚蠢的原因:

如果只有一个相关模型的实例,那么过滤器根本不会显示。在本例中,RelatedFieldListFilter 类中有一个 has_output() 方法返回 False

Another very dumb cause of the same problem:

If there is only one instance of the related model, then the filter simply won't show. There is a has_output() method in RelatedFieldListFilter class that returns False in this case.

热鲨 2024-11-10 21:13:29

这肯定是一个奇怪的问题。在 AdBase 模型上,如果您更改

advertiser = models.ForeignKey(Advertiser)

adver = models.ForeignKey(Advertiser)

,那么我相信它会显示出来。

It's a strange problem for sure. On the AdBase model if you change

advertiser = models.ForeignKey(Advertiser)

to

adver = models.ForeignKey(Advertiser)

then I believe it'll show up.

梦在深巷 2024-11-10 21:13:29

Powellc,您是否已使用各自的 ModelAdmin 类注册了模型?

ModelAdmin 定义之后的 admin.site.register(Advertiser, AdvertiserAdmin)

Powellc, do you have the models registered with their respective ModelAdmin class?

admin.site.register(Advertiser, AdvertiserAdmin) after the ModelAdmin definitions.

无畏 2024-11-10 21:13:29

您正在谈论 list_display 选项,对吧?

unicode< /a>-您的相关模型集的方法?

如果字段是外键,Django
将显示 unicode()
相关对象

另请检查此线程以获取一些提示: Can "list_display" in a Django ModelAdmin display attribute offoreignKey fields?

You are talking about the list_display option, right?

Is the unicode-method for your related model set?

If the field is a ForeignKey, Django
will display the unicode() of the
related object

Also check this thread for some hints: Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

牵你的手,一向走下去 2024-11-10 21:13:29

尝试禁用您的广告拦截器。不,这不是玩笑。我刚刚遇到了这个问题。

Try disabling your ad blocker. No, this is not a joke. I just ran into this exact problem.

倥絔 2024-11-10 21:13:29

我们刚刚遇到了这个问题。

看来,如果您在管理员中称呼您为现场广告商,则会获得“广告商”类别。

然后被标准广告拦截插件隐藏。如果你查看源代码,你的字段就会在那里。

We just ran into this problem.

It seems that if you call you field advertiser the in the admin the gets given an 'advertiser' class.

Then is then hidden by standard ad blocking plugins. If you view source your field will be there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文