Giter VIP home page Giter VIP logo

flask_table's Introduction

Flask Table

Because writing HTML is fiddly and all of your tables are basically the same.

Build Status Coverage Status PyPI version

Installation

pip install flask-table

Quick Start

# import things
from flask_table import Table, Col

# Declare your table
class ItemTable(Table):
    name = Col('Name')
    description = Col('Description')

# Get some objects
class Item(object):
    def __init__(self, name, description):
        self.name = name
        self.description = description
items = [Item('Name1', 'Description1'),
         Item('Name2', 'Description2'),
         Item('Name3', 'Description3')]
# Or, equivalently, some dicts
items = [dict(name='Name1', description='Description1'),
         dict(name='Name2', description='Description2'),
         dict(name='Name3', description='Description3')]

# Or, more likely, load items from your database with something like
items = ItemModel.query.all()

# Populate the table
table = ItemTable(items)

# Print the html
print(table.__html__())
# or just {{ table }} from within a Jinja template

Which gives something like:

<table>
<thead><tr><th>Name</th><th>Description</th></tr></thead>
<tbody>
<tr><td>Name1</td><td>Description1</td></tr>
<tr><td>Name2</td><td>Description2</td></tr>
<tr><td>Name3</td><td>Description3</td></tr>
</tbody>
</table>

Or as HTML:

NameDescription
Name1Description1
Name2Description2
Name3Description3

For more, see the examples for some complete, runnable demonstrations.

Extra things:

  • The attribute used for each column in the declaration of the column is used as the default thing to lookup in each item.

  • The thing that you pass when you populate the table must:

    • be iterable
    • contain dicts or objects - there's nothing saying it can't contain some of each. See examples/simple_sqlalchemy.py for a database example.
  • You can pass attributes to the td and th elements by passing a dict of attributes as td_html_attrs or th_html_attrs when creating a Col. Or as column_html_attrs to apply the attributes to both the ths and the tds. (Any that you pass in th_html_attrs or td_html_attrs will overwrite any that you also pass with column_html_attrs.) See examples/column_html_attrs.py for more.

  • There are also LinkCol and ButtonCol that allow links and buttons, which is where the Flask-specific-ness comes in.

  • There are also DateCol and DatetimeCol that format dates and datetimes.

  • Oh, and BoolCol, which does Yes/No.

  • But most importantly, Col is easy to subclass.

Table configuration and options

The following options configure table-level options:

  • thead_classes - a list of classes to set on the <thead> element.

  • no_items - a string to display if no items are passed, defaults to 'No Items'.

  • html_attrs - a dictionary of attributes to set on the <table> element.

  • classes - a list of strings to be set as the class attribute on the <table> element.

  • table_id - a string to set as the id attribute on the <table> element.

  • border - whether the border should be set on the <table> element.

These can be set in a few different ways:

a) set when defining the table class

class MyTable
    classes = ['class1', 'class2']

b) passed in the options argument to create_table.

MyTable = create_table(options={'table_id': 'my-table-id'})

c) passed to the table's __init__

table = MyTable(items, no_items='There is nothing', ...)

Note that a) and b) define an attribute on the table class, but c) defines an attribute on the instance, so anything set like in c) will override anything set in a) or b).

Eg:

class ItemTable(Table):
    classes = ['myclass']
    name = Col('Name')
table = ItemTable(items, classes=['otherclass'])

would create a table with class="otherclass".

Included Col Types

  • OptCol - converts values according to a dictionary of choices. Eg for turning stored codes into human readable text.

  • BoolCol (subclass of OptCol) - converts values to yes/no.

  • BoolNaCol (subclass of BoolCol) - converts values to yes/no/na.

  • DateCol - for dates (uses format_date from babel.dates).

  • DatetimeCol - for date-times (uses format_datetime from babel.dates).

  • LinkCol - creates a link by specifying an endpoint and url_kwargs.

  • ButtonCol (subclass of LinkCol) creates a button that posts the the given address.

  • NestedTableCol - allows nesting of tables inside columns

More about OptCol

When creating the column, you pass some choices. This should be a dict with the keys being the values that will be found on the item's attribute, and the values will be the text to be displayed.

You can also set a default_key, or a default_value. The default value will be used if the value found from the item isn't in the choices dict. The default key works in much the same way, but means that if your default is already in your choices, you can just point to it rather than repeat it.

And you can use coerce_fn if you need to alter the value from the item before looking it up in the dict.

More about BoolCol

A subclass of OptCol where the choices are:

{True: 'Yes', False: 'No'}

and the coerce_fn is bool. So the value from the item is coerced to a bool and then looked up in the choices to get the text to display.

If you want to specify something other than "Yes" and "No", you can pass yes_display and/or no_display when creating the column. Eg:

class MyTable(Table):
    mybool = BoolCol('myboolcol', yes_display='Affirmative', no_display='Negatory')

More about BoolNaCol

Just like BoolCol, except displays None as "N/A". Can override with the na_display argument.

More about DateCol

Requires Babel configuration

Formats a date from the item. Can specify a date_format to use, which defaults to 'short', which is passed to babel.dates.format_date.

More about DatetimeCol

Requires Babel configuration

Formats a datetime from the item. Can specify a datetime_format to use, which defaults to 'short', which is passed to babel.dates.format_datetime.

Babel configuration

Babel uses a locale to determine how to format dates. It falls back to using environment variables (LC_TIME, LANGUAGE, LC_ALL, LC_CTYPE, LANG), or can be configured within Flask, allowing dynamic selection of locale.

Make sure that one of the following is true:

  • at least one of the above environment variables is set to a valid locale
  • BABEL_DEFAULT_LOCALE is set as config on the Flask app to a valid locale
  • a @babel.localeselector function is configured

Note that Babel reads the environment variables at import time, so if you set these within Python, make sure it happens before you import Flask Table. The other two options would be considered "better", largely for this reason.

More about LinkCol

Gives a way of putting a link into a td. You must specify an endpoint for the url. You should also specify some url_kwargs. This should be a dict which will be passed as the second argument of url_for, except the values will be treated as attributes to be looked up on the item. These keys obey the same rules as elsewhere, so can be things like 'category.name' or ('category', 'name').

The kwarg url_kwargs_extra allows passing of contants to the url. This can be useful for adding constant GET params to a url.

The text for the link is acquired in almost the same way as with other columns. However, other columns can be given no attr or attr_list and will use the attribute that the column was given in the table class, but LinkCol does not, and instead falls back to the heading of the column. This make more sense for things like an "Edit" link. You can override this fallback with the text_fallback kwarg.

Set attributes for anchor tag by passing anchor_attrs:

name = LinkCol('Name', 'single_item', url_kwargs=dict(id='id'), anchor_attrs={'class': 'myclass'})

More about ButtonCol

Has all the same options as LinkCol but instead adds a form and a button that gets posted to the url.

You can pass a dict of attributes to add to the button element with the button_attrs kwarg.

You can pass a dict of attributes to add to the form element with the form_attrs kwarg.

You can pass a dict of hidden fields to add into the form element with the form_hidden_fields kwargs. The keys will be used as the name attributes and the values as the value attributes.

More about NestedTableCol

This column type makes it possible to nest tables in columns. For each nested table column you need to define a subclass of Table as you normally would when defining a table. The name of that Table sub-class is the second argument to NestedTableCol.

Eg:

class MySubTable(Table):
    a = Col('1st nested table col')
    b = Col('2nd nested table col')

class MainTable(Table):
    id = Col('id')
    objects = NestedTableCol('objects', MySubTable)

Subclassing Col

(Look in examples/subclassing.py for a more concrete example)

Suppose our item has an attribute, but we don't want to output the value directly, we need to alter it first. If the value that we get from the item gives us all the information we need, then we can just override the td_format method:

class LangCol(Col):
    def td_format(self, content):
        if content == 'en_GB':
            return 'British English'
        elif content == 'de_DE':
            return 'German'
        elif content == 'fr_FR':
            return 'French'
        else:
            return 'Not Specified'

If you need access to all of information in the item, then we can go a stage earlier in the process and override the td_contents method:

from flask import Markup

def td_contents(self, i, attr_list):
    # by default this does
    # return self.td_format(self.from_attr_list(i, attr_list))
    return Markup.escape(self.from_attr_list(i, attr_list) + ' for ' + item.name)

At present, you do still need to be careful about escaping things as you override these methods. Also, because of the way that the Markup class works, you need to be careful about how you concatenate these with other strings.

Manipulating <tr>s

(Look in examples/rows.py for a more concrete example)

Suppose you want to change something about the tr element for some or all items. You can do this by overriding your table's get_tr_attrs method. By default, this method returns an empty dict.

So, we might want to use something like:

class ItemTable(Table):
    name = Col('Name')
    description = Col('Description')

    def get_tr_attrs(self, item):
        if item.important():
            return {'class': 'important'}
        else:
            return {}

which would give all trs for items that returned a true value for the important() method, a class of "important".

Dynamically Creating Tables

(Look in examples/dynamic.py for a more concrete example)

You can define a table dynamically too.

TableCls = create_table('TableCls')\
    .add_column('name', Col('Name'))\
    .add_column('description', Col('Description'))

which is equivalent to

class TableCls(Table):
    name = Col('Name')
    description = Col('Description')

but makes it easier to add columns dynamically.

For example, you may wish to only add a column based on a condition.

TableCls = create_table('TableCls')\
    .add_column('name', Col('Name'))

if condition:
    TableCls.add_column('description', Col('Description'))

which is equivalent to

class TableCls(Table):
    name = Col('Name')
    description = Col('Description', show=condition)

thanks to the show option. Use whichever you think makes your code more readable. Though you may still need the dynamic option for something like

TableCls = create_table('TableCls')
for i in range(num):
    TableCls.add_column(str(i), Col(str(i)))

We can also set some extra options to the table class by passing options parameter to create_table():

tbl_options = dict(
    classes=['cls1', 'cls2'],
    thead_classes=['cls_head1', 'cls_head2'],
    no_items='Empty')
TableCls = create_table(options=tbl_options)

# equals to

class TableCls(Table):
    classes = ['cls1', 'cls2']
    thead_classes = ['cls_head1', 'cls_head2']
    no_items = 'Empty'

Sortable Tables

(Look in examples/sortable.py for a more concrete example)

Define a table and set its allow_sort attribute to True. Now all columns will be default try to turn their header into a link for sorting, unless you set allow_sort to False for a column.

You also must declare a sort_url method for that table. Given a col_key, this determines the url for link in the header. If reverse is True, then that means that the table has just been sorted by that column and the url can adjust accordingly, ie to now give the address for the table sorted in the reverse direction. It is, however, entirely up to your flask view method to interpret the values given to it from this url and to order the results before giving the to the table. The table itself will not do any reordering of the items it is given.

class SortableTable(Table):
    name = Col('Name')
    allow_sort = True

    def sort_url(self, col_key, reverse=False):
        if reverse:
            direction =  'desc'
        else:
            direction = 'asc'
        return url_for('index', sort=col_key, direction=direction)

The Examples

The examples directory contains a few pieces of sample code to show some of the concepts and features. They are all intended to be runnable. Some of them just output the code they generate, but some (just one, sortable.py, at present) actually creates a Flask app that you can access.

You should be able to just run them directly with python, but if you have cloned the repository for the sake of dev, and created a virtualenv, you may find that they generate an import error for flask_table. This is because flask_table hasn't been installed, and can be rectified by running something like PYTHONPATH=.:./lib/python3.3/site-packages python examples/simple.py, which will use the local version of flask_table including any changes.

Also, if there is anything that you think is not clear and would be helped by an example, please just ask and I'll happily write one. Only you can help me realise which bits are tricky or non-obvious and help me to work on explaining the bits that need explaining.

Other Things

At the time of first writing, I was not aware of the work of Django-Tables. However, I have now found it and started adapting ideas from it, where appropriate. For example, allowing items to be dicts as well as objects.

flask_table's People

Contributors

benediktseidl avatar jonathanunderwood avatar nichannah avatar nullptrt avatar plumdog avatar pnpie avatar volter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask_table's Issues

RawCol using Jinja2 statements

Hi Andrew,

I am trying to implement a select2 box for each row into my table. The select2 box is using Jinja2 statements with values provided by the python app itself:

image

so, in my table definition I copied the select box coding into a RawCol for this purpose and it seems the table is not able to render this in the right order or he tries to instantiate the select box already by the time of table creation and not at runtime.

image
image

result:
image

The same seems to be using wtforms:
image

result:
image

any idea how to treat this best?

regards Michael

creting a table

I am trying to make a dynamic table.
created the table, added the columns, but now how to I pass my list of dictionaries?

TableCls = flask_table.create_table('TableCls')
for i in range(0, 20):
    TableCls.add_column(str(i), flask_table.Col(str(i)))

TableCls.items = items_list  # not sure how to inject my itemlist into the flask_table class so it render properly with flask.


return render_template(table=TableCls)

thanks =)

freezing table headers

Hi Andrew,

I was wondering if there is a way to freeze the header to support users with long lists. Once you start to scroll, the header disappears.
I look for something like in Excel, Freeze header.
Was already looking into bootstrap, but could not find anything usefull, except responsive table definition which was not doing anything different then before:

image

regards
Michael

input tag issue

What should I do if I want to add a input filed in a cell? If I directly set the cell as '', the tag chars will be changed to &gt and &lt. If you have any idea on solving it or if there is some alternative on achieving my goal, please tell me. Thanks a lot.

sort_url not implemented in setup guide in readme

When following the setup in the readme I receive the warning that not all abstract methods have been implemented, it seems the sort_url method has been left out of the readme.

Possibly consider adding this to the readme?

Example using SQLAlchemy?

Hi,

Would you be able to write up an example where you create a table from an sqlalchemy table or query_set?

AttributeError: type object 'Item' has no attribute 'query' [python3]

// Excuse my beginner's English
Hi!

I use python3.4 and flask

So, i just run 'example' code and occure exception:

Traceback (most recent call last):
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3.4/dist-packages/flask/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3.4/dist-packages/flask/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/python3.4/dist-packages/flask/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/var/www/store-system.podarok.boutique/index.py", line 41, in hello
    items = Item.query.all()
AttributeError: type object 'Item' has no attribute 'query'

Thanks!

Deprecation warning on Python 3.5

Getting a deprecation warning on Python 3.5 wen importing Table and Col. It's related to an import that doesn't appear to be used.

Hopefully this is an easy fix.

$ cat /etc/issue
Ubuntu 16.04.1 LTS \n \l
$ uname -a
Linux nylon 4.4.0-45-generic #66-Ubuntu SMP Wed Oct 19 14:12:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask_table import Table, Col
/usr/local/lib/python3.5/dist-packages/flask_table/columns.py:5: ExtDeprecationWarning: Importing flask.ext.babel is deprecated, use flask_babel instead.
 from flask.ext.babel import gettext as _
>>> 

aligning cell contents (left, right, center, top, botton...)

Hi,

I created a dynamic table and the header-labels are wider than the individual contents of the rows. (see attachment)
padding
I am able to format the values based on python 'format coding' but I seem not to be able to 'right-align' the values with this coding. He seems to ignore '>' or not supported with flask_table at all?

value assignment to flask_table variable:
list[entry.name] = '{:>,.2f}'.format(value).replace(",", "X").replace(".", ",").replace("X", ".")

Is there a way to specify the position (left, right, center, top, bottom) of the values in the cells?

regards
Michael

setting id on table tag

How can i set the table tag id to 'table' so the HTML output looks like this: '<table id='table'>'
Is there a way to pass any tags i want?

Rendering a Flask-table for a wtforms FieldList(FormField(SomeForm)

Hi, I've been trying to modify this library to be able to generate a dynamic table with input fields that can work with a FieldList(FormField(SomeForm) structure. I have a form like below:

class InputGridRecordForm(NavForm):
    """A form for entering inputgrid record row data"""
    id = IntegerField('Continent Record ID')
    select = BooleanField('Select')
    stringcol1 = StringField('String Col #1')
    intcol1 = IntegerField('Int Col #1')

class InputGridTableForm(NavForm):
    """A form for one or more InputGridRecords"""
    gridtblrecords = FieldList(FormField(InputGridRecordForm), min_entries=1)

If I render the body of this form without Flask-Table then the <tbody> basically looks like below:

<tbody>
    {{ form.csrf_token }}
    {% for grid_record in form.gridtblrecords %}
    <tr>
        {% for field in grid_record %}
        <td>{{ field() }}</td>
            {% endfor %}
     </tr>
    {% endfor %}
</tbody>

It would be nice if this worked with flask-table but I need to find a way to get the jinja for-loops working right and it's been a no-go so far. Here is (some) of what I've tried.

Override tbody for the outer loop:

    def tbody(self):
        out = [self.tr(item) for item in self.items]
        if out:
            return Template('<tbody>{% for form in form.gridtblrecords %}'
                            '\n{0}\n{% endfor %}'
                            '</tbody>').render(form=self.form).format('\n'.join(out))
       else:
           return '' 

Override tr_format for the inner loop:

    def tr_format(self, item):
    """Returns the string that is formatted with the contents of the
    tr. Override this if you want to alter the attributes of the
    tr.
    """
    return Template(
                    '<tr>'
                    '{% for field in grid_record %}'
                    '{}'
                    '{% endfor %}'
                    '</tr>'
                    ).render(form=self.form)

I've done a few different things for the column classes but it seems I should just be able to return a string of the different fields in a jinja template braces and it should render in the tr_format.

class InputStringCol1(Col):
     """Make a column that can accept inputs"""
         def td_format(self, content):
         """formats the <td> to accept an input"""
         safe_content = super(InputStringCol1, self).td_format(content)
         return ='{{ field.stringcol1 }}'

Anyway, want to check to see if you've already tackled this or have any feedback - which is much appreciated!

Create empty table

Hi there,
For some "odd?" reason I need to create an empty table, by that I mean no and . Just

and the header is required.
Is that possible?

Thanks
//M

Using a table instance in a template

So I have created my table using create_table and added a bunch of class instances to it. I can get the raw html with table.html(). What I want to do is embed the table in page that is created with render_template('.show_stuff', table=table)

If I put {{ table.html() }} in show_stuff.html I see the actual html not the table. Is there a trick to getting the table's html to render in the template?

Thanks,

  • Craig

Creating an empty column, or column with static content

Hi there, first off thanks for the great plugin -- it's going to save me so much time fiddling with tables!

I am using DataTables and I want to add an empty column for checkboxes (to select rows) like in this example.

Can you think of an easy way to do this with flask_table? Again -- thanks a lot!

import fails on heroku due to encoding issue

When I attempted to install this package on heroku, it fails to import:

>>> from flask_table import Table, Col, BoolCol, DateCol, LinkCol
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/app/.heroku/python/lib/python2.7/site-packages/flask_table/__init__.py", line 1, in <module>
    from .table import Table
  File "/app/.heroku/python/lib/python2.7/site-packages/flask_table/table.py", line 82
SyntaxError: Non-ASCII character '\xe2' in file /app/.heroku/python/lib/python2.7/site-packages/flask_table/table.py on line 82, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Just thought I'd let you know-- great work otherwise!

Investigate better Pandas DataFrame integration

Originally raised in #93, but I think there could be more to investigate here.

(Note: I am not a Pandas user, so any input from anyone who has ever used it would be great!)

A DataFrame broadly speaking looks a lot like a table, with columns and some data. And the pattern of "I have lots of data in a DataFrame, I want to throw it at a table and look at in a Flask app" seems like it could be pretty common.

It might well be that this comes in the form of more of a recipe (and put into examples/), than actual code in the package. A dependency on pandas would be bad, but something to make using it with pandas easier would be lovely.

Is there a way to set <table id='123'... ?

Hello,

I'm pretty sure my question can be easily answered and that I'm missing something that is just too simple.

I basically need to add an id='...' field for each table I create - how can I go about doing so?

Google has turned its back to me on this one..

Thanks
//M

Enable documentation generation inside the repo

Have you consider using Sphinx or similar?
It may allow other people may help you write documentation, for examples with PR.

In case you don't have time or will,
i may prepare a PR to include documentation generated in markdown with mkdocs. I may simply convert your readme in mkdocs template so that you can enable autogeneration on websites like readthedocs.

Paolo

ButtonCol - anchor_attr and Column naming

Hi Andrew,

I have 2 topics in regards to ButtonCol functionalities:

I am trying to use the anchor_attr to specify a bootstrap Class for the button but it seems he is ignoring it:

coding:
image

result:
image

html:
image

further I am trying to give the column header a different name, but he is using the '+' for both, column-header and the button itself.
Would like to name the column-header 'Action' and the buttons with a '+'.

Thanks for the support
Michael

Add a CHANGELOG

And make it so the release.sh script writes stuff to this.

Impossible to make href links work properly

I'm trying to make a web-page that displays a bunch of values from MongoDB, here is my code:

class LangCol(Col):             # This lets me get a webaddress into the table
    def td_format(self, content):
        parsed=urllib.parse.unquote(content)
        split = urlsplit(parsed)

        return ('<a href='+("".join(['http://',split.netloc, split.path]))+ '>'+content+'</a>')



class ItemTable(Table):
    ID = Col('IDs')
    type = Col("type")
    Job_URL = LangCol("URL")

items = mongodb.bdb.find({"OS" : "CentOS7.3"})
items2 = mongodb.bdb.find({"OS" : "RHEL7.3"})
# Get some objects
#class Item(object):
#    def __init__(self, name, description):
#        self.name = name
#        self.description = description
#items = [Item('Job1', 'Job1'),
#         Item('Job2', 'Job2'),
#         Item('Job3', 'Job3')]


app = Flask(__name__)

@app.route('/')
def index():
    table = ItemTable(items)
    table2 = ItemTable(items2)
    return table.__html__()

The relevant code is the return statement of LangCol
I've tried other returns, such as (the one I REALLY hoped would worked)

return ('<a href='+content+ '>'+content+'</a>')

Unfortunately, no matter what I do, I either get a URL that includes my hosted flask server
(like http://127.0.0.1:5000/http%3A//10.23.182.101%3A8080/job/%28CHPC%29%20Factory%20-%20CentOS%207.3%20x86_TS/57/)
or, if I unquote my weburl instead, it will truncate everything after part of my link
(like http://10.23.182.101:8080/job/(CHPC) )

This issue is very frustrating, because the closest thing to a solution I've found looks like it should, but doesn't work correctly.

https://stackoverflow.com/questions/17056408/flask-jinja2-href-not-linking-correctly

As we can see, content displays the exact URL correctly on the page. I want this exact URL to be a clickable hyperlink to the address that it prints. Unfortunately, this seems to be impossible.

screenshot from 2017-07-07 06-38-24

I'm an intern at a large tech company which probably makes your CPU, and I (along with my team) am very inexperienced with web technologies. Apologies if I'm doing something silly and don't notice it.

Give the possibility to add a specific class to thead

Hello,
if you see how css frameworks work
(e.g. bootstrap http://v4-alpha.getbootstrap.com/content/tables/#table-head-options)
it would be conveniente to have a way to add a thead class like the table class option.

For now i patched with:

class ItemTable(Table):
    def thead(self):
        return '<thead class="thead-default"><tr>{}</tr></thead>'\
            .format(''.join( (self.th(col_key, col) \
            for col_key, col in self._cols.items() if col.show)))

Thanks for this great plugin,
Paolo

Table attributes

What if I want to add something like <table border=1>. I think right now it's not possible (and I know I could do it with CSS classes) - but would you be OK if I do a pull request implementing this?

Creating a sortable table with toggling of the sort direction column

I have gone through the examples and I have successfully created a sortable table which is working brilliantly. I did not manage to see any options for allowing the sorting of a column to be toggled, ie if sort direction is asc after first clicking of the header, a second clicking the header results in the sort direction reversing to desc.
Please advise if this already is available or if it is to added at some point in the future.

Pandas

Any direct integration available to pandas DataFrame object to create tables?

jinja not rendering table?

I am writing something up based on the docs but I have an issue I can't figure out.

Basically the table is created fine, and when explicitly printing the <table>.__html__() I can see it is generating the html but Jinja is not replacing the tag with the html. For simplicity sake I have:

class myTable():
    <stuff>

hTable = myTable(myTable.getItems()) # the getItems method just runs a static query and fills the results

Then in the html file, lets call it myHtml.html:

<stuff>

{{ hTable }}

<other stuff>

Is this not correct? I'm not terribly sure.

As I said, when I do

print(hTable.__html__())

it is definitely producing the correct html but maybe I am missing how to pass it to jinja?

No Example of using DateTime Column

Happy to find this great package I have implemented it in production! ๐ŸŽ‰
But even after extensive searching I failed to find an example stating how to use DateTime Column.
I don't know if this is the correct place to ask this question.
Any help would be greatly appreciated. ๐Ÿ™‡


Found this in the docs

Formats a datetime from the item. Can specify a datetime_format to use, which defaults to 'short', which is passed to babel.dates.format_datetime.

Could someone please post a minimal working example of DateTime ? My current Columns show time in the long format including pico seconds (maybe)

additional header <tr> and summarized values in <tfood>

Hi Andrew,

In my target table, I use a seperate <tr> inside the header (above the column description) to specify a factor for the SUM values later in the <tfoot> tag.

  1. Is there a way to specify an additional <tr> tag inside the header as coded below?
  2. how do I specify a <tfood> tag that summarises the values of the tables for each column, using also the "factor" given from the header <input> field?

would like to get a result something like this:

image

<table>
  <thead>
    <tr>
      <th>factor SUM</th>
      <th><input type="number" name="factor_savings" value=2></th>
    </tr>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$360</td>
    </tr>
  </tfoot>
</table>

thanks
Michael

Adding classes to table

In table.py the current code inserts a space to the class argument. I'm not sure if this is on purpose (I have no familiarity with this package). From what I can tell this prevents the class being set correctly when html is generated.

This could be fixed by removing space from line 53.
return ' class="{}"'.format(' '.join(self.classes))

to

return ' class="{}"'.format(''.join(self.classes))

Specifying datetime_format for DatetimeCol raises TypeError

Creating a table as

class ModemConnectionTable(flask_table.Table):
    time = flask_table.DatetimeCol('time', datetime_format='YYYY-MM-dd hh:mm')

raises

File ".../site-packages/flask_table/columns.py", line 175, in __init__
    Col.__init__(self, name, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'datetime_format'

since Col.__init__ is called with the same arguments as DatetimeCol, but does not take any **kwargs

DateTest & DatetimeTest are affected by the locale + Continuous Integration

Hi! Some tests are affected by the default locale of the machine.

In order to run the tests on my machine (Switzerland) I needed to set the locale to the one I assume you're using - and it seems babel.dates checks the environment var LC_TIME first, so I needed to do this to get all the tests to pass:

export LC_TIME="en_UK.UTF-8"
# then run the tests
 nosetests -v

I would be up to contribute to set up travis to do automated tests per Pull Request...

Table class option for dynamic create_table

At the moment create_table works only with the original Table.
If i extend that class, i cannot use it in a dynamic way.

Please provide an additional option to use a different Table class.

Thanks!
Paolo

Support for nesting tables

I have a use case where I want to nest a table inside the main table in one of the columns. I've managed to get something working by subclassing Col for that column, and hand producing the nested table html inside the td_format method for that Col subclass.

But it would be nice if there was a more elegant way of allowing nesting. I'm playing around with various ideas currently, but haven't come up with a decent deign, so I thought I'd open an issue to see if you could see an easy way to achieve this :).

sortable.py question

I'm trying to use flask-table to create sortable tables in a Flask app I've created. I've been playing around with the sortable.py example and have hit a problem.

The issue I'm having is that I don't know what the columns are going to be until runtime. Is there a way to initialize the SortableTable class with Col instances at runtime?

I tried this

class SortableTable(Table):
    def __init__(self, *args, **kwargs):
        super(SortableTable, self).__init__(*args, **kwargs)
        SortableTable.__dict__['id'] = Col("ID")
        SortableTable.__dict__['name'] = Col("Name")
        SortableTable.__dict__['Description'] = Col("Description")
        SortableTable.__dict['link'] = LinkCol('Link', 'flask_link', url_kwargs=dict(id='id'), allow_sort=False)

    etc

With hopes that I could later instantiate table by including a list of (attrName, colTitle) tuples to loop through.

But when I call table = SortableTable(Item.get_sorted_by(sort, reverse), sort_by=sort, sort_reverse=reverse)

I get an exception saying the dict_proxy does not support item assignment. I thought that perhaps I needed to set up the columns before calling the superclass' init method, so I put the super call after dict assignment lines and got the same error.

Is there a way to define columns at runtime?

Thanks,
Craig

def "sort_url" for dynamic tables

Hi,
-- Warning, May be a greenhorn qustion -- :-)
I have designed a dynamic table based on create_table function and try to use the sort functionality as well. As per documentation the sort_url function is specified to the class Table itself. But with dynamic tables I do not a class like class TableCls(Table):
Where do I define the "def sort_url" function when using dynamic tables created with:
TableCls = create_table('TableCls') ?

regards#
Michael

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.