Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow max_length to be picked up automatically #11

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ A simple django widget that appends a character count to a text input which is d
## Installation

The package can be installed via:

pip install git+https://github.com/timmyomahony/django-charsleft-widget.git


## Usage

Expand All @@ -20,9 +20,7 @@ class Song(models.Model):
title = models.CharField(max_length=100)
```

then create a custom model form that uses the custom widget class. **Note that it's important
to include the `maxlength` attribute manually when making use of the widget, as it will not
be pulled in automatically from your model field.**
then create a custom model form that uses the custom widget class.

```python
from django import forms
Expand All @@ -31,7 +29,7 @@ from charsleft_widget.widgets import CharsLeftInput
from .models import Song

class SongForm(forms.ModelForm):
name = forms.CharField(widget=CharsLeftInput(attrs={'maxlength': 100}))
name = forms.CharField(widget=CharsLeftInput())

class Meta:
model = Song
Expand All @@ -51,4 +49,11 @@ from .forms import SongForm
@admin.register(Song)
class SongAdmin(admin.ModelAdmin):
form = SongForm
```
```


You can optionally toggle off the color changing feature by initialising the widget (from the example above) with:

```python
name = forms.CharField(widget=CharsLeftInput(attrs={'change_color': False}))
```
2 changes: 1 addition & 1 deletion charsleft_widget/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
VERSION = ("0","1","0")
VERSION = ("0","1","1")
37 changes: 20 additions & 17 deletions charsleft_widget/static/charsleft-widget/js/charsleft.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
(function($){
(function($){
$.fn.charsLeft = function(options){
var defaults = {
var defaults = {
'source':'input',
'dest':'.count',
}
var options = $.extend(defaults, options);
var calculate = function(source, dest, maxlength){

var calculate = function(source, dest, maxlength, changeColor){
var remaining = maxlength - source.val().length;
dest.html(remaining);
/* Over 50%, change colour to orange */
p = (100 * remaining) / maxlength;
if(p < 25){
dest.addClass('orange');
}else if(p < 50){
dest.addClass('red');
}else{
dest.removeClass('orange red');

if (changeColor) {
/* Over 50%, change colour to orange */
p = (100 * remaining) / maxlength;
if(p < 25){
dest.addClass('orange');
}else if(p < 50){
dest.addClass('red');
}else{
dest.removeClass('orange red');
}
}
};

this.each(function(i, el) {
var maxlength = $(this).find('.maxlength').html();
var dest = $(this).find(options.dest);
var source = $(this).find(options.source);
var changeColor = source.attr('change_color') !== undefined;
source.keyup(function(){
calculate(source, dest, maxlength)
calculate(source, dest, maxlength, changeColor)
});
source.change(function(){
calculate(source, dest, maxlength)
calculate(source, dest, maxlength, changeColor)
});
});
};
Expand All @@ -38,5 +42,4 @@
'dest':".count",
});
});
})(django.jQuery);

})((typeof django !== 'undefined' && django.jQuery) || window.jQuery || jQuery);
8 changes: 8 additions & 0 deletions charsleft_widget/templates/charsleft_widget/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% load i18n %}
<span class="charsleft charsleft-input">
<input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %}>
<span class="charsleft-input-text">
<span class="count">{{ current_count }}</span>{% trans 'characters remaining' %}</span>
<span class="maxlength">{{ widget.attrs.maxlength }}</span>
</span>
</span>
59 changes: 19 additions & 40 deletions charsleft_widget/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,50 +18,29 @@
from charsleft_widget.utils import compatible_staticpath


class CharsLeftInput(forms.TextInput):
class CharsLeftInput(forms.TextInput):
template_name = 'charsleft_widget/input.html'
type = 'text'

class Media:
css={
"all": ("charsleft-widget/css/charsleft.css", )
}
js=(compatible_staticpath("charsleft-widget/js/charsleft.js"), )

def render(self, name, value, attrs=None, **kwargs):
if value is None:
value = ''

extra_attrs = {
'type': self.input_type,
'name': name,
'maxlength': self.attrs.get('maxlength')
}

# Signature for build_attrs changed in 1.11
# https://code.djangoproject.com/ticket/28095
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, **extra_attrs)
else:
final_attrs = self.build_attrs(attrs, extra_attrs=extra_attrs)

if value != '':
final_attrs['value'] = force_str(self._format_value(value))

maxlength = final_attrs.get('maxlength', False)
if not maxlength:
return mark_safe(u'<input%s />' % flatatt(final_attrs))

current = force_str(int(maxlength) - len(value))
html = u"""
<span class="charsleft charsleft-input">
<input %(attrs)s />
<span>
<span class="count">%(current)s</span> %(char_remain_str)s</span>
<span class="maxlength">%(maxlength)s</span>
</span>
""" % {
'attrs': flatatt(final_attrs),
'current': current,
'char_remain_str': _(u'characters remaining'),
'maxlength': int(maxlength),
}
return mark_safe(html)
def __init__(self, attrs=None):
"""
Override init to initialise change_color attribute
"""
if attrs is None:
attrs = {}
# If change_color present in widget attrs use the value, otherwise it's True by default
attrs.setdefault('change_color', True)
super().__init__(attrs)

def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context['widget']['type'] = self.input_type
maxlength = int(context['widget']['attrs'].get('maxlength', attrs.get('maxlength', 0)))
context['current_count'] = force_str(maxlength - len(value)) if value else '0'
return context