I have googled and googled for an answer, but I can't seem to find one.
How do I make mongoengine check for a unique value in a case insensitive way? Because right now if I create an entry with, let's say, '[email protected]', it lets me create a new entry with '[email protected]". How do I solve this issue, in a clean way? (Not using .lower)
models.py:
from flask_mongoengine import MongoEngine
db = MongoEngine()
class User(db.Document):
email = db.EmailField(
unique = True,
required = True
)
username = db.StringField(
unique = True,
required = True
)
password = db.StringField(
required = True
)
def to_json(self):
return {
'email': self.email,
'username': self.username,
'password': self.password
}
auth.py:
from flask import Blueprint, render_template, request, flash, redirect
from werkzeug.security import generate_password_hash
from models import User, db
import re
auth = Blueprint('auth', __name__)
@auth.route('/signup', methods = ('GET', 'POST'))
def signup():
if request.method == 'POST':
email = request.form['email']
username = request.form['username']
password = generate_password_hash(request.form['password'])
user = User(
email = email,
username = username,
password = password
)
try:
user.save()
flash(f'Account successfully created.', 'success')
except Exception as e:
flash(f'Email or username already in use.', 'error')
# return "Error \n %s" % (e)
return render_template('signup.html')
CodePudding user response:
You can make the unique index on the email field to be case insensitive by declaring the index specification in the meta dictionary.
class User(db.Document):
email = db.EmailField(
required = True
)
username = db.StringField(
unique = True,
required = True
)
password = db.StringField(
required = True
)
meta = {
"indexes": [
{
"fields": ["email"],
"unique": True,
"collation": { "locale": "en", "strength": 2 } }
}
]
}