Giter Site home page Giter Site logo

plumdog / flask_table Goto Github PK

View Code? Open in Web Editor NEW
208.0 13.0 44.0 229 KB

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

Home Page: http://flask-table.readthedocs.org/

License: BSD 3-Clause "New" or "Revised" License

Python 77.49% Shell 5.79% HTML 16.72%
python flask table html

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

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?

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.

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.

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.

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

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 :).

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!

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 =)

Add a CHANGELOG

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

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!

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?

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!

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

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

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

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

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

Pandas

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

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

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

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!

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

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 _
>>> 

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)

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))

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

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

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

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

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

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?

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.

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?

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?

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...

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.