Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow_tags=True does not render <form> tag in django admin

I want to display a form in the list_display in django admin, but I'm facing this problem:

when I define something like this:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('foo', 'pagar_pase')

    def pagar_pase(self, obj):
        return """<form action="." method="post">Action</form> """
    pagar_pase.description = 'Testing form output'
    pagar_pase.allow_tags = True

and the result is Action without tags, any ideas how to solve this?

thanks

like image 945
pahko Avatar asked Sep 20 '25 06:09

pahko


1 Answers

Here's what appears in the documentation. Few hints:

I think you should include pagar_pase in your list_display tuple and also you are better off using format_html than the triple quotes.

from django.utils.html import format_html

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    def colored_name(self):
        return format_html('<span style="color: #{0};">{1} {2}</span>',
                           self.color_code,
                           self.first_name,
                           self.last_name)

    colored_name.allow_tags = True

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')

Here, they define first the model and then create a ModelAdmin and there, they include the method's name in the list_display which you're missing.

Your code should be like this:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('foo', 'my_custom_display', 'pagar_pase')

    def pagar_pase(self, obj):
        # I like more format_html here.
        return """<form action="." method="post">Action</form> """
    pagar_pase.description = 'Testing form output'
    pagar_pase.allow_tags = True

Hope it helps!

like image 102
Paulo Bu Avatar answered Sep 21 '25 23:09

Paulo Bu