R
R
realgord882015-07-23 13:15:04
SQLite
realgord88, 2015-07-23 13:15:04

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

2 answer(s)
D
Dmitry Filimonov, 2015-07-23
@realgord88

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

ps If the result of the query is not needed, then you can look at exists() . I do not think that it is critical for this kind of tasks, but data is not uploaded with it.

V
Vladimir Abiduev, 2015-07-24
@gunlinux

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 question

Ask a Question

731 491 924 answers to any question