inlines -django

时间:2009-05-21 09:33:42

标签: django-admin django-forms

我有2个模型。我想让model2与model1内联。在管理页面上,我想将一些模型2的字段显示为内联,并将所有字段显示为readonly.ALso当我点击的值时内联我应该将我链接到带有该值的model2

以只读方式显示字段的内联。我想将内联模型字段显示为只读

1 个答案:

答案 0 :(得分:7)

由于newforms管理员,这(通常)很容易做到。基本上,您需要创建自定义内联子类并覆盖用于在管理中呈现它的模板。假设您有一个名为app且模型Model1Model2的应用,您可以执行以下操作:

首先,创建您的admin.py文件:

from django.contrib import admin
from app.models import Model1, Model2

class Model2Admin(admin.ModelAdmin):
    list_display = (...)

class Model2Inline(admin.TabularInline):
    model = Model2
    extra = 0
    template = 'admin/app/model2/inline.html'

class Model1Admin(admin.ModelAdmin):
    list_display = (...)
    inlines = (Model2Inline,)

admin.site.register(Model1, Model1Admin)
admin.site.register(Model2, Model2Admin)

然后,在inline.html创建admin/app/model2模板:

{% load i18n %}
<div class="inline-group">
  <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">
    {{ inline_admin_formset.formset.management_form }}
    <fieldset class="module">
      <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst|escape }}</h2>
      {{ inline_admin_formset.formset.non_form_errors }}
      <table>
        <thead>
          <tr>
            <th colspan="2">Field1</th>
            <th>Field2</th>
            <th>Field3</th>
          </tr>
        </thead>

        {% for inline_admin_form in inline_admin_formset %}
          <tr class="{% cycle row1,row2 %}">
            <td class="original">
              <!-- Render all form fields as hidden fields: -->
              {{ inline_admin_form.pk_field.field }}
              {% spaceless %}
              {% for fieldset in inline_admin_form %}
                {% for line in fieldset %}
                  {% for field in line %}
                    {{ field.field.as_hidden }}
                  {% endfor %}
                {% endfor %}
              {% endfor %}
              {% endspaceless %}
            </td>

            <!-- then display just the values of the fields you're interested in: -->
            <td class="field1">
              <!-- Make this a link to the change detail page for this object: -->
              <a href="{% url admin:app_model2_change inline_admin_form.original.pk %}">{{ inline_admin_form.original.field1 }}</a>
            </td>
            <td class="field2">
              {{ inline_admin_form.original.field2 }}
            </td>
            <td class="field3">
              {{ inline_admin_form.original.field3 }}
            </td>
        </tr>
      {% endfor %}
      </table>
    </fieldset>
  </div>
</div>

接下来,将您的应用添加到INSTALLED_APPS中的settings.py - 请不要忘记添加django.contrib.admin :)。

最后,编辑根urls.py以包含以下行:

from django.conf.urls.defaults import *
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
   ...
   (r'^admin/', include(admin.site.urls))
)

应该这样做。请注意,admin.site.urls,使网址反转成为可能,只会在django 1.1之后发挥作用。