views:

379

answers:

2

Hello everyone,

I have a field in a model that I want users to feel like they can write an arbitrary amount of text in. Django provides a CharField and a TextField in the models. I assume that the difference is that one of them is a char(max_length) and the other is a varchar internally.

I am tempted to use the TextField, but since it doesn't respect max_length, I am somewhat wary of someone dumping loads of data into it and DOSing my server. How should I deal with this?

Thanks!

+5  A: 

Fields in model only represent the way data is stored in database.

You can very easily enforce maximum length in form which will validate users' input. Like this.

class InputForm(forms.Form):
    text = forms.CharField(max_length=16384, widget=forms.TextArea)
    ...

This will make sure the maximum length user can successfully enter is 16k.

af
Too bad, I wish I could just use ModelForm without modifying the representation. I like keeping magic numbers all in one place :-)
SapphireSun
Actually, you can still use ModelForm and just customize it for that field. See http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#overriding-the-default-field-types
af
It should say widget=forms.Textarea instead of forms.TextArea.
Gerald Senarclens de Grancy
A: 

It is more an html limitation than django's one. A way to overcome it is in javascript. This is the simpliest solution:

<script language="javascript" type="text/javascript">
<!--
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}
-->
</script> 

Implementation:
<textarea name="myName" onkeypress="return imposeMaxLength(this, 15);" ><textarea>

This solution is re-usable for all text areas via one function and it doesn't inform the user that he/she is typing too many characters, it prevents them from doing so, sort of like maxlength

It could be used in both user forms and in admin interface.

Double-checking the length of the incoming GET/POST data would also be useful to avoid dos-attacks (in case they manually override this javascript limitation).

Antony Hatchkins
The problem with JS is that it's all client side. If I don't trust them in the first place, I'm not trusting the JS code to execute ;-)
SapphireSun