Django:如何在admin / index.html中为特定模型添加新按钮

时间:2015-06-17 14:04:50

标签: django django-admin

我正在覆盖admin / index.html内容块。 我有这个内容:

{% for model in app.models %}
        <tr class="model-{{ model.object_name|lower }}">
        {% if model.admin_url %}
            <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th>
        {% else %}
            <th scope="row">{{ model.name }}</th>
        {% endif %}

        {% if model.add_url %}
            <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td>
        {% else %}
            <td>&nbsp;</td>
        {% endif %}

        {% if model.admin_url %}
            <td><a href="{{ model.admin_url }}" class="changelink">{% trans 'Change' %}</a></td>
        {% else %}
            <td>&nbsp;</td>
        {% endif %}
        </tr>
    {% endfor %}

我的模特是:

class Schedule(models.Model):
    active = models.BooleanField(default=True, null=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=False)
    price_percent_lower = models.DecimalField(max_digits=2, decimal_places=1, null=False, default=1.3)
    price_percent_highter = models.DecimalField(max_digits=2, decimal_places=1, null=False)

如何创建一个新的按钮,例如<a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a>指向仅针对此模型的名为 do_a_thing()的方法?

1 个答案:

答案 0 :(得分:1)

如果您只需要在模板上调用do_a_thing,那么这应该有效。

{% if model.object_name == 'Schedule' %}
<a href="{{ model.do_a_thing }}" class="custom-class">{% trans 'Do a thing' %}</a>
{% endif %}

在模特中

class Schedule(models.Model):
    active = models.BooleanField(default=True, null=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=False)
    price_percent_lower = models.DecimalField(max_digits=2, decimal_places=1, null=False, default=1.3)
    price_percent_highter = models.DecimalField(max_digits=2, decimal_places=1, null=False)

   @classmethod
   def do_a_thing(cls):
      ...

如果您需要添加观看,请参阅http://patrick.arminio.info/additional-admin-views/