#Is there an easy way to set the background color of rows in the changelist view?

5 messages · Page 1 of 1 (latest)

static raft
#

I know that I could write my own page to do this, instead of over-relying on the admin; but before I do that, I'd like to be sure there's no easy way to get the admin to do this.
If you look at the usual "poll" app from the tutorial:

https://imgur.com/a/rKEGZnU

I'd like the row whose question text is "blue" to be colored blue, and the row whose text is "red" to be colored red. In general, I'd like to write a bit of code somewhere that

  • gets the value of the question column
  • uses that as the key to a table, to get (say) a hex code for color
  • somehow applies that color to the row

Is this easily doable?

static raft
#

This kinda does it for just that one column: ```py
@admin.display(description="Color")
def colored_question(self):
return format_html(
'<span style="background-color: {};"><tt>....</tt></span>{}',
self.question.lower().replace(" ", ""),
self.question,
)

cerulean palm
#

Maybe you could make colored_question output e.g. <span class="blue">... and then add some custom CSS with .changelist tr:has(span.blue) ... ? Just throwing some ideas out there and hoping it helps somewhat.

If a simple CSS solution is not sufficient I think I'd write some JavaScript. Customizing the ChangeList with some JS code is relatively straightforward, but it also tends to break between releases when the HTML is changed a lot. I mostly only use this technique in OSS projects where I have unittests which verify that the behaviors still work.

static raft
#

I don't think using class is any better than style, because (I assume) in both cases the effect is confined to just one column.

In case it's not clear, I only have a dim understanding of CSS 🙂

cerulean palm
#

@static raft The advantage of using class would be that you can use :has to target tr elements which contain elements having the particular class. It sounds like that's a bit too advanced or specific. If you're happy with only coloring a cell and not the row: Do what you're doing currently. If you need to color the whole row, write some JavaScript which lifts the style from the cell to the row, or maybe, maybe use the :has trick I mentioned. But yeah, I'd recommend either the simple version of only coloring the cell or the hacky version of writing JavaScript to apply styles to the row.