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

后端 未结 3 1444
抹茶落季
抹茶落季 2021-01-14 12:21

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(adm         


        
相关标签:
3条回答
  • 2021-01-14 12:32

    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!

    0 讨论(0)
  • 2021-01-14 12:35

    Ok, so the problem here is that list_display is inside an html form, so I was trying to display a form inside a form, that is a bad idea... and below explains why

    Can you nest html forms?

    Hope it helps.

    0 讨论(0)
  • 2021-01-14 12:38

    It looks like you are trying to trigger an action on an item listed. Perhaps this is better executed by writing your own admin actions.

    Here is an example:

    def pagar_pase(modeladmin, request, queryset):
        """ Does something with each objects selected """
        selected_objects = queryset.all()
        for i in selected_objects:
            # do something with i
    
    pagar_pase.short_description = 'Testing form output'
    
    class MyModelAdmin(admin.ModelAdmin):
        list_display = ('foo', 'my_custom_display')
        actions = [pagar_pase]
    
    0 讨论(0)
提交回复
热议问题