View returns URL with column data if model has get_absolute_url attribute
If the model used for the view has get_absolute_url()
method, the view will send all model's column as <a>
tags.
Suggestion:
- To have an option to render the columns with the link. (Easy)
- To have an option to map column with the link. (Advance)
Comments (7)
-
reporter -
reporter Case
Model
class Dummy(models.Model): first_name = CharField() last_name = CharField() def get_absolute_url(self): reutrn 'blah/blah'
View
class DummyView(BaseDatatableView): columns = ['first_name', 'last_name']
JSON response
{ "draw": 1, "recordsTotal": 1, "recordsFiltered": 1, "data":[["<a href=\"/blah/blah\">first_name</a>" , "<a href=\"/blah/blah\">last_name</a>"]], "result": "ok" }
I want to control which field rendered as anchor tag and which is just plain text.
I have some ideas, I will create a PR this weekend.
-
repo owner Isn't it enough to override render_column method, eg.:
def render_column(self, row, column): if column == 'first_name': return '<a href="{}">{}</a>'.format(row.get_absolute_url(), row.first_name) return super().render_column(row, column)
-
reporter I think I didn't explain my idea well.
Because of this code
def render_column(self, row, column): """ Renders a column on a row. column can be given in a module notation eg. document.invoice.type """ ... if value and hasattr(obj, 'get_absolute_url'): return '<a href="%s">%s</a>' % (obj.get_absolute_url(), value) return value
If the model object has
get_absolute_url()
method, the model attributes will be rendered as HTML anchor tag. With this code part, I can't control which column should be rendered as an anchor tag. -
I second this. With a large model and get_absolute_url in the model, all columns show as anchor tags. So I ended up having to override the render_column for ALL columns to remove it. Would be nice to have a flag to turn it off, then we can add it to a specific column if we want it as your example above. or use a column list of columns we WANT to be anchored.
-
repo owner - changed status to resolved
In the 1.19.1 render_column has been split into two methods so that it should be now easy to only add <a> tag to some columns
-
Awesome, thanks!
By changing my subclass render_column to return super()._render_column it allowed me to remove my workaround.
- Log in to comment