Skip to content

Instantly share code, notes, and snippets.

@ricardodani
Last active March 20, 2022 14:37
Show Gist options
  • Save ricardodani/090255c2700d794ee65ac1aa47172e11 to your computer and use it in GitHub Desktop.
Save ricardodani/090255c2700d794ee65ac1aa47172e11 to your computer and use it in GitHub Desktop.
django admin textarea widget char counter
# admin
from django import admin
from django.db import models
from widget import TextareaWithCounter
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TextareaWithCounter},
}
class Media:
css = {
"all": ("textareacounter/textareacounter.css", )
}
js = ("textareacounter/textareacounter.js", )
.counter {
display: inline-block;
vertical-align: bottom;
margin-left: 10px;
}
.counter .input-counter {
font-weight: bold;
}
(function($) {
$(function() {
$('textarea.textareacounter').change(function(e) {
e.preventDefault();
$(this).siblings('.counter').find('.input-counter').html(
$(this).val().length
);
});
$('textarea.textareacounter').keyup(function(e) {
$(this).change();
})
})
})(django.jQuery);
# wiget
from django.forms.widgets import Textarea
class TextareaWithCounter(Textarea):
def render(self, name, value, attrs=None):
attrs.update({'class': 'textareacounter'})
ret_html = super(TextareaWithCounter, self).render(name, value, attrs)
return ('{}<div class="counter"><span class="input-counter">'
'{}</span> chars</div>').format(ret_html, len(value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment