Home > Back-end >  How to display current user's username in URL Flask
How to display current user's username in URL Flask

Time:09-28

I am trying to add my current user's username to my URL(route), but I keep on getting errors. I have tried many things as mentioned below but nothing is working. Here is my code:

@app.route("/settings/<string:Users_username>" , methods=["GET", "POST"])
def settings(Users_username):
    user = Users.query.filter_by(username=Users_username)
    return render_template("settings.html", user=user )

Layout.html:

<a href="{{url_for('settings', Users_username = user.username )}}" target="_blank" 
rel="noopener noreferrer">Settings</a>

I get the error when I try to go to another page and 404 when I go to settings.

jinja2.exceptions.UndefinedError

jinja2.exceptions.UndefinedError: 'user' is undefined

enter image description here

MODELS.py

@login_manager.user_loader
def load_user(user_id):
   return Users.query.get(int(user_id))

class Users(db.Model, UserMixin):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String, unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

Is something wrong in layout.html or my routes.html? This is basically a function, that when settings is clicked takes you to settings page and I want the username of the logged in user to appear in URL.When I change my layout.html, then I get

404 error: Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again

I have made sure user is logged in:{% if current_user.is_authenticated %} I also tried changing routes.py as:

@app.route("/settings/<string:Users_username>" , methods=["GET", "POST"])
def settings(Users_username):
    user = Users.query.filter_by(username=Users_username)
    return render_template("settings.html", user=user.username )

Rest is same (settings function). This change gave error:

AttributeError: 'BaseQuery' object has no attribute 'username'

CodePudding user response:

Try this user = Users().query.filter_by(username=Users_username).first().

And you don't need to give a string as a converter type in your url because it is string by default. Have a look here

CodePudding user response:

@Reef is almost correct : In the function settings(Users_username) replace :

user = Users.query.filter_by(username=Users_username)

by

user = Users.query.filter_by(username=Users_username).first()

(or better first_or_404() is you are using Flask-Sqlalchemy)

CodePudding user response:

After 3 days of research and desire for answers, reading multiple articles watching countless videos, just randomly tried this in layout.html which worked!!

<a href="{{ url_for('user', Users_username = current_user.username ) }}" 
target="_blank" rel="noopener noreferrer">Settings</a>

Now no need for database queries in settings function!

  • Related