microblog icon indicating copy to clipboard operation
microblog copied to clipboard

7.6 Fixing the duplicate username bug in edit-profile

Open ikamran opened this issue 3 years ago • 1 comments

in the form.py to validate user you sent the current user in routes.py form = EditProfileForm(current_user.username)

then in forms.py

class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
    submit = SubmitField('Submit')
    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username
    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please use a different username.')

the question is why you don't used just import current_user and check it out?


def validate_username(self, username):
        if username.data != current_user.username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please use a different username.')

Thanks for your help

ikamran avatar Oct 18 '21 23:10 ikamran

Because that creates a dependency between Flask-WTF and Flask-Login. Having code that depends on too many things is bad, because the more dependencies the less portable the code is. So basically, there is nothing wrong with your proposed approach, but I consider mine better.

miguelgrinberg avatar Oct 19 '21 06:10 miguelgrinberg