Make input field remove newlines from value

170 views
Skip to first unread message

Jakub Kleň

unread,
Nov 1, 2018, 8:14:48 PM11/1/18
to Django developers (Contributions to Django itself)
I created this ticked today, and it got closed with a wontfix flag, but I still think it would be a good idea to implement:
https://code.djangoproject.com/ticket/29912

The reason why it got closed is that django shouldn't modify the input like that, but the link which is mentioned in the response talks about stripping spaces from beginning and end of values, which was resigned some time ago, but It's now a part of django. All form fields automatically strip spaces from beginning and end after submission. It's even the default behaviour, although it's optional.

The next thing that is mentioned in the reply, is that the input may come from an API. I understand this change would be backwards incompatible, it it's turned on by default, but there's no problem in managing this. There could be a flag for it on django.forms.fields.CharField, and ModelForm could automatically enable/disable it the same as it assigns the TextInput / Textarea widget. It seems right to me to differentiate between single line / multiline fields. I was thinking on how to resolve this issue today, and as I have 23 forms in my project, it seemed error-prone to do it in Form.clean_xxx, in so many places.

As a temporary solution, I implemented it for django.forms.widgets.Input by overriding value_from_datadict (monkey patch, which i would definitely like to remove in the future).

From the logical standpoint, it seems relevant to me to implement such a functionality for <input> fields. From my point of view, the main difference between an <input> and a <textarea> is that input is just for one-line values, whereas a textarea is used when you need a multiline input from the user. Even web browsers have this restriction, and I think it would be a bit safer and more consistent. It took me a while to realise that I should remove newlines for all my input fields. Maybe it's not even such a bad idea to implement it in the widgets, as I'm thinking about it. It would be a lot easier, and maybe it's even the right place for it.

Carlton Gibson

unread,
Nov 2, 2018, 6:43:41 AM11/2/18
to Django developers (Contributions to Django itself)
Hi Jakub. 

Definitely stripping input isn't something I'd want to add: what if I want to accept input with trailing whitespace? 

Rather, the approach is to transform the incoming data in your form or serialiser at the clean or validation step. 

See: 


If you're sure you want the stripped value, I don't see anything wrong with a custom widget, as you've used. 
(I don't see it as a monkey patch: custom widgets are not an anti-pattern — there's no way we can account for every use-case in the core framework.) 

Thus, I agree with the wontfix here. 

Kind Regards,

Carlton
Reply all
Reply to author
Forward
0 new messages