【问题标题】:Editable related model fields in Django admin?Django admin中可编辑的相关模型字段?
【发布时间】:2014-07-10 03:49:24
【问题描述】:

阅读 Django 管理站点的文档后,我仍然不确定如何通过保持以下规则直接在表单中添加相关模型的字段:

  • 不允许直接修改模型源。只有猴子修补或子类化是可能的。
  • 需要在表单的字段集中的现有字段之间插入,不需要在单独的内联管理模型中插入
  • 字段需要可编辑,相关模型记录在表单保存时更新

简化示例如下:

from django.db import models
from django import forms

class Order(models.Model):
    contact = models.ForeignKey(Contact, verbose_name=_('Contact'))
    bill_addressee = models.CharField(_("Addressee"), blank=True)

class Contact:
    email = models.EmailField(_("Email"), blank=True, max_length=75)

class OrderAdminForm(forms.ModelForm):
    fieldsets = (
        (_('Billing Address'), {'classes': ('collapse',), 'fields': (
           'organization_name', 'bill_addressee', 'bill_street1', 'bill_city',
           'email',) })
        #  ^^^^^^ <-- need related model field directly
        )

    class Meta:
        model = Order

对于只读字段,这是非常简单的任务。只需定义返回相关模型字段的方法并放入readonly_fields 属性。但是可编辑呢?

【问题讨论】:

    标签: python django django-models django-forms django-admin


    【解决方案1】:

    您可以简单地将 Contact.email 包含在“字段”列表中:

    'fields': ('organization_name', 'bill_addressee', 'Contact.email',)
    

    【讨论】:

    • 已尝试但出现以下错误:ImproperlyConfigured: 'OrderAdminForm.fieldsets[3][1]['fields']' refers to field 'Contact.email' that is missing from the form.。你确定可以这样引用国外模型字段吗?
    • 不工作:Unknown field(s) (foo.bar) specified for Baz.
    猜你喜欢
    • 1970-01-01
    • 2016-12-11
    • 2014-09-04
    • 2018-01-10
    • 2015-05-21
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2011-12-13
    相关资源
    最近更新 更多