Last active
March 20, 2022 14:37
-
-
Save ricardodani/090255c2700d794ee65ac1aa47172e11 to your computer and use it in GitHub Desktop.
django admin textarea widget char counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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", ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.counter { | |
display: inline-block; | |
vertical-align: bottom; | |
margin-left: 10px; | |
} | |
.counter .input-counter { | |
font-weight: bold; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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