开发者

Django - admin changeForm extra content beside a field

开发者 https://www.devze.com 2023-04-01 01:59 出处:网络
In the admin change_form of one of my objects I need to have extra content in a certain field (like buttons which will do some javascript modifications on this field)

In the admin change_form of one of my objects I need to have extra content in a certain field (like buttons which will do some javascript modifications on this field)

I took a look at the original change_form template and I see that I can add things to the block content but how can I add that just beside a certain field ?

Example:

<!-- ... -->
<div class="form-row part">
  <div>
    <label for="id_part" class="required">Part:</label>
    <input id="id_part" type="text" class="vIntegerField" value="1" name="part" />
  </div>
</div>
<div class="form-row text">
  <div>
    <label for="id_text" class="required">Text:</label>
    <textarea id="id_text" rows="10" cols="40" name="text" class="vLargeTextField"></textarea>
  </div>
</div>
<div class="form-row sequence">
  <div>
    <label for="id_sequence" class="required">Sequence:</label>
    <input id="id_sequence" type="text" class="vIntegerField" value="3" name="sequence" />
  </div>
</div>
<!-- ... -->

Would become

<!-- ... -->
<div class="form-row part">
  <div>
    <label for="id_part" class="required">Part:</label>
    <input id="id_part" type="text" class="vIntegerField" value="1" name="part" />
  </div>
</div>
<div class="form-row text">
  <div>
    <label for="id_text" class="required">Text:</label>
    <textarea id="id_text" rows="10" cols="40" name="text" class="vLargeTextFie开发者_JAVA技巧ld"></textarea>
  </div>
<!-- extra content start -->
  <div class="markup-tools">
    <input type="button" class="tool1" value="Tool 1" />
    <input type="button" class="tool2" value="Tool 2" />
    <input type="button" class="tool3" value="Tool 3" />
  </div>
<!-- extra content end -->
</div>
<div class="form-row sequence">
  <div>
    <label for="id_sequence" class="required">Sequence:</label>
    <input id="id_sequence" type="text" class="vIntegerField" value="3" name="sequence" />
  </div>
</div>
<!-- ... -->

Is there a way to do that without having to append the content with JS like:

$('.form-row.text').append('the content');

I find that not very maintainable


Yes, there is, but the js way is much easier.

You need to create a custom widget class, then set the particular field to use that widget. Example:

class FooWidget(Widget):
    def render(self, *args, **kwargs):
        output = super(FooWidget, self).render(*args, **kwargs)
        output += "<p>I'm a widget!</p>"
        return mark_safe(output)

class BarAdmin(ModelAdmin):
    formfield_overrides = { models.TextField: {'widget': FooWidget} }

This will override all TextField fields with your custom FooWidget.


Aparently not.

I had to do several

$('.form-row.text').append('the content');

To put extra content

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号