P
P
Pavel2017-02-14 06:21:17
Flask
Pavel, 2017-02-14 06:21:17

Flask. How to edit a profile through the form?

I can't figure out how to implement the validation stage for profile editing. How to implement profile editing form without JS? If the user changes, for example, the postal address, then all fields come into validation, including those that have not changed. All data is validated for uniqueness, and the user already has data that does not change naturally.
Or am I doing it wrong by not separating the admin panel and the user function to change their data?

class User(UserMixin, SurrogatePK, Model):
    """A user of the app."""

    __tablename__ = 'users'
    username = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    password = Column(db.Binary(128), nullable=True)

class UserEditForm(Form):
    """Register form."""

    username = StringField('Username',
                           validators=[Optional(), Length(min=3, max=25)])
    email = StringField('Email',
                        validators=[Email(), Length(min=6, max=40)])
    password = PasswordField('Password',
                             validators=[Optional(), Length(min=6, max=40)])

    def __init__(self, *args, **kwargs):
        """Create instance."""
        super(UserEditForm, self).__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        """Validate the form."""
        initial_validation = super(RegisterForm, self).validate()
        if not initial_validation:
            return False
        user = User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append('Username already registered')
            return False
        user = User.query.filter_by(email=self.email.data).first()
        if user:
            self.email.errors.append('Email already registered')
            return False
        return True

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question