Answer the question
In order to leave comments, you need to log in
How to check Nickname uniqueness in SQLAlchemy Flask/Python DB?
You need to check the uniqueness of the nickname when registering users. I tried this code, it doesn't work. What are your suggestions, comrades?
from flask import render_template, flash, redirect, session, url_for, request, g
from app import app, db, models
from models import User, ROLE_USER, ROLE_ADMIN
from forms import RegisterForm
import flask
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
form = RegisterForm()
ROLE_USER = 0
counter = 0
nick = ''
if form.validate_on_submit():
user = User(nickname = form.Nickname.data, email = form.Email.data, password = form.Password.data, role = ROLE_USER)
users = models.User.query.all()
for u in users:
nick = u.id,u.nickname
if nick == form.Nickname.data:
counter += 1
if counter == 0:
db.session.add(user)
db.session.commit()
return redirect('/')
else:
flash('ebat ti loh')
return render_template('index.html',
form = form,
counter = counter,
nick = nick)
Answer the question
In order to leave comments, you need to log in
Make a unique index on the nickname attribute in the User model. Something like this: nickname = Column(..., unique=True)
And check like this:
try:
user = User.query.filter_by(nickname=user.nickname).one()
except NoResultFound:
# ник уникален
pass
else:
# ник не уникален
pass
Let flask-wtf
parse
class RegistrationForm(Form):
email = StringField(u'Электронная почта',
validators=[Required(REQ_TEXT),
Length(1, 64),
Email(REQ_TEXT)])
password = PasswordField(u'Пароль', validators=[
Required(REQ_TEXT)])
submit = SubmitField(u'Зарегистрироваться')
def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError(u'Почта уже занята')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question