Force all email addresses coming in to lowercase

1,320 views
Skip to first unread message

Chris Foresman

unread,
Mar 4, 2015, 11:53:08 PM3/4/15
to django-res...@googlegroups.com
I want all email addresses to be converted to lowercase before being saved to the database. My guess is I have to create a custom serializer field and put `data.lower()` in `to_internal_value()`. Does that sound right?

Tom Christie

unread,
Mar 5, 2015, 4:04:55 AM3/5/15
to django-res...@googlegroups.com
> My guess is I have to create a custom serializer field and put `data.lower()` in `to_internal_value()`. Does that sound right?

Yup.

You can also use the `validate_<fieldname>()` or `validate()` methods on the serializer class as a shortcut. 

Jeppe Vesterbæk

unread,
Mar 5, 2015, 7:18:33 AM3/5/15
to django-res...@googlegroups.com
A side note: If you are using postgres and your goal is to keep email adresses unique, case invariant - but want to keep emails in their original casing (since the name part is case sensitive in theory/spec), you could do a validation with lookup case insensitive and then add a functional index ala

CREATE UNIQUE INDEX email_lower_index On user (lower(email));

That index should also be used when doing the case insensitive lookup for validation

From here:

Chris Foresman

unread,
Mar 5, 2015, 11:00:52 AM3/5/15
to django-res...@googlegroups.com
Tom,

If I override `validate_email()` on the serializer, do I then need to pull in the Django regex and apply that manually?


Jeppe,

That;s a sweet hint, but in our case I'm going to lowercase everything as it comes in. On the other hand, usernames will have preserved case but comparisons are case insensitive for uniqueness; I think I can use this hint there.



Thanks,
Chris Foresman



--
You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/W_FXICKWvOQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages