最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Django: Using textarea widget with javascript character counterlimiter? - Stack Overflow

programmeradmin0浏览0评论

I am trying to use a textarea form entry which I have some javascript code to count and limit the character count, whose max_length and size are dynamic (ie these attributes are alterable after model creation).

In order to include this functionality in the django form textarea widget I suppose I would have to create a custom widget, although im not sure how to tie in the javascript code in the template really. For changing the textarea size, i suppose I would pass a variable into the form creation from the view to generate the textarea widget instance.

Otherwise for now I am simply creating the inputs in the template in html/js and then submitting the POST data to the django view, and retrieving it using getitem, then saving the data directly to my models. Which works of course, but is not very django'y, and perhaps is somehow vulnerable without the built-in django validation and clean data functions.

So two questions I guess: (a) If I create a custom django form widget, how do I apply my javascript function to the textarea fields in the template (includes "onkeypress=jstextcounter...") and (b) If I continue just retrieving the post data in the view without a django form, is there a vulnerability and what should I do to ensure the data is well-validated? (page already requires user login, not a public ment box)

Or maybe someone has created such a custom form widget before and knows a good snippet somewhere?

Cheers...

EDIT So thanks to MovieYoda's help, I got this working and some reading over dynamic forms in django. And with a %d substitute I can dynamically change the maxChars attribute for my js function.

In forms.py I have:

text=forms.CharField(max_length = 1000, widget=forms.widgets.Textarea())

def __init__(self, *args, **kwargs):
     size = kwargs.pop('size')
     maxChars = kwargs.pop('maxChars') 
     super(MyForm, self).__init__(*args, **kwargs)
     self.fields['text'].widget.attrs['onkeypress'] = 'return textCounter(this, this.form.counter, %d);' % maxChars
     self.fields['text'].widget.attrs['rows'] = size
     self.fields['text'].widget.attrs['cols'] = '40'

Where the js function 'textCounter' in the template is limiting the number of characters, using the maxChars variable.

<script type="text/javascript">

function textCounter( field, countfield, maxLimit) {
  if ( field.value.length > maxLimit )
  {
    field.value = field.value.substring( 0, maxLimit );
    return false;
  }
  else
  { 
    countfield.value = maxLimit - field.value.length;
  }
}
</script>

And in the view create the form with the kwargs inputs:

FormInstance = MyForm(size=1, maxChars=5)

I am trying to use a textarea form entry which I have some javascript code to count and limit the character count, whose max_length and size are dynamic (ie these attributes are alterable after model creation).

In order to include this functionality in the django form textarea widget I suppose I would have to create a custom widget, although im not sure how to tie in the javascript code in the template really. For changing the textarea size, i suppose I would pass a variable into the form creation from the view to generate the textarea widget instance.

Otherwise for now I am simply creating the inputs in the template in html/js and then submitting the POST data to the django view, and retrieving it using getitem, then saving the data directly to my models. Which works of course, but is not very django'y, and perhaps is somehow vulnerable without the built-in django validation and clean data functions.

So two questions I guess: (a) If I create a custom django form widget, how do I apply my javascript function to the textarea fields in the template (includes "onkeypress=jstextcounter...") and (b) If I continue just retrieving the post data in the view without a django form, is there a vulnerability and what should I do to ensure the data is well-validated? (page already requires user login, not a public ment box)

Or maybe someone has created such a custom form widget before and knows a good snippet somewhere?

Cheers...

EDIT So thanks to MovieYoda's help, I got this working and some reading over dynamic forms in django. And with a %d substitute I can dynamically change the maxChars attribute for my js function.

In forms.py I have:

text=forms.CharField(max_length = 1000, widget=forms.widgets.Textarea())

def __init__(self, *args, **kwargs):
     size = kwargs.pop('size')
     maxChars = kwargs.pop('maxChars') 
     super(MyForm, self).__init__(*args, **kwargs)
     self.fields['text'].widget.attrs['onkeypress'] = 'return textCounter(this, this.form.counter, %d);' % maxChars
     self.fields['text'].widget.attrs['rows'] = size
     self.fields['text'].widget.attrs['cols'] = '40'

Where the js function 'textCounter' in the template is limiting the number of characters, using the maxChars variable.

<script type="text/javascript">

function textCounter( field, countfield, maxLimit) {
  if ( field.value.length > maxLimit )
  {
    field.value = field.value.substring( 0, maxLimit );
    return false;
  }
  else
  { 
    countfield.value = maxLimit - field.value.length;
  }
}
</script>

And in the view create the form with the kwargs inputs:

FormInstance = MyForm(size=1, maxChars=5)
Share Improve this question edited May 23, 2017 at 10:26 CommunityBot 11 silver badge asked Nov 26, 2010 at 12:32 HdN8HdN8 3,2093 gold badges26 silver badges26 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

(a) If I create a custom django form widget, how do I apply my javascript function to the textarea fields in the template (includes "onkeypress=jstextcounter...") and

From what I was able to understand you want to define javascript handlers on your form elements? Here's how one can approach this -

In forms.py

class Search(forms.Form):
 se=forms.CharField(widget=forms.TextInput(attrs={'onClick':'return jscode();'}))

Now render your form as usual. In your js file, write this handler function jscode() & make it do what you want.

(b) If I continue just retrieving the post data in the view without a django form, is there a vulnerability and what should I do to ensure the data is well-validated?

The second part can also be easily handled. In your forms.py file define these member functions for which you want to do some data-validation. You can do it like this -

class Search(forms.Form):
 se=forms.CharField(widget=forms.TextInput(attrs={'onClick':'return jscode();'}))
 def clean_se(self):
    #do your validaton here. In case of error raise ValidationError.
    raise forms.ValidationError('Passwords do not match.')

Note that the clean fn. should be in this format - clean_<field_to_be_cleaned>. Here it is se. so...

Apart from Making sure @login_required - which makes sure your view is accessed by a logged in user, you need to use csrf_token in your form templates & urlencode your data (if user submits some data through the form). Now you are good to go...

This jQuery library does what you're after. It shows the user how many characters they have remaining as well as limiting the input.

Download and reference the library here and use the following code to call it:

<script type="text/javascript">
    $(document).ready(function () {
        $("#textarea1").CharacterCount({
            charactersRemainingControlId: "remainingCount1"
        });
    });
</script>       

<textarea id="textarea1" name="textarea1" cols="20" rows="3" maxlength="10"></textarea>

The number of characters left is: <span id="remainingCount1">0</span>
发布评论

评论列表(0)

  1. 暂无评论