简体   繁体   中英

Django-tables2 subclass error (class attributes not passed to instantiated object)

I'm using django-tables2 and trying to create a new DeleteColumn class:

tables.py

class DeleteColumn(tables.TemplateColumn):
    def __init__(self, *args, **kwargs):
        super(DeleteColumn, self).__init__(*args, **kwargs)

        self.template_name='wakemeup/admin/delete_link.html'
        self.verbose_name=''

class SchoolsTable(tables.Table):
    test = DeleteColumn()

    class Meta:
        model = School

I keep getting this error, though: ValueError: A template must be provided

Am I not creating the class properly? Why doesn't the template_name value specified in the class get passed along when creating a new instance of DeleteColumn ?

Can someone please point me in the right direction?

If you take a look at the source of TemplateColumn ( http://django-tables2.readthedocs.io/en/latest/_modules/django_tables2/columns/templatecolumn.html ) you'll see that __init__() checks for a template_column or template_name attribute and if neither is found the ValueError you mention is thrown.

Now the problem is that you set the template_name attribute after you have called super(...).__init__ in your class, thus the template_name attribute is empty!

Edited

Sorry I didn't check the source code very thouroughly, it's been written in a funny way and doesn't use the attributes. In any case, from what I see now, you'll need to override __init__ to pass the template_name parameter to the parent's init, something like this:

class DeleteColumn(tables.TemplateColumn):
    def __init__(self, *args, **kwargs):
        # This will pass ``template_name`` to the super().__init__ along with any args and kwargs
        super(DeleteColumn, self).__init__(*args, template_name='wakemeup/admin/delete_link.html', **kwargs)
        self.verbose_name=''

I hope it works now!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM