In Python Flask, how to get the role name by the current logged in user?How do I copy a file in Python?How can I safely create a nested directory in Python?How to get the current time in PythonHow can I make a time delay in Python?Getting the class name of an instance?Getting the last element of a list in PythonHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How do I lowercase a string in Python?SQLAlchemy relationships, when to use which relationship?

Why don't electromagnetic waves interact with each other?

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

Why CLRS example on residual networks does not follows its formula?

What are these boxed doors outside store fronts in New York?

Why don't electron-positron collisions release infinite energy?

What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)

How do I create uniquely male characters?

What defenses are there against being summoned by the Gate spell?

Writing rule which states that two causes for the same superpower is bad writing

Shell script not opening as desktop application

Why are only specific transaction types accepted into the mempool?

Infinite past with a beginning?

How is this relation reflexive?

Why can't I see bouncing of a switch on an oscilloscope?

Why Is Death Allowed In the Matrix?

Why was the small council so happy for Tyrion to become the Master of Coin?

Can I interfere when another PC is about to be attacked?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

What is the offset in a seaplane's hull?

Is there a familial term for apples and pears?

declaring a variable twice in IIFE

A function which translates a sentence to title-case

Proof for divisibility of polynomials.

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?



In Python Flask, how to get the role name by the current logged in user?


How do I copy a file in Python?How can I safely create a nested directory in Python?How to get the current time in PythonHow can I make a time delay in Python?Getting the class name of an instance?Getting the last element of a list in PythonHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How do I lowercase a string in Python?SQLAlchemy relationships, when to use which relationship?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?



In my models.py



class User(db.Model, UserMixin):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')

# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
__tablename__ = 'Roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
__tablename__ = 'UserRoles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))


In my views.py:



from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
role = current_user.role
return str(role)


On the browser, it shows me the returned result:



SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id


Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?



role = current_user.role.name









share|improve this question






















  • Try user_roles = [role.name for role in current_user.roles]

    – tntxtnt
    Mar 9 at 4:27











  • Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

    – Andrew Allen
    Mar 11 at 16:19

















0















I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?



In my models.py



class User(db.Model, UserMixin):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')

# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
__tablename__ = 'Roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
__tablename__ = 'UserRoles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))


In my views.py:



from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
role = current_user.role
return str(role)


On the browser, it shows me the returned result:



SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id


Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?



role = current_user.role.name









share|improve this question






















  • Try user_roles = [role.name for role in current_user.roles]

    – tntxtnt
    Mar 9 at 4:27











  • Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

    – Andrew Allen
    Mar 11 at 16:19













0












0








0








I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?



In my models.py



class User(db.Model, UserMixin):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')

# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
__tablename__ = 'Roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
__tablename__ = 'UserRoles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))


In my views.py:



from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
role = current_user.role
return str(role)


On the browser, it shows me the returned result:



SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id


Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?



role = current_user.role.name









share|improve this question














I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?



In my models.py



class User(db.Model, UserMixin):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')

# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
__tablename__ = 'Roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
__tablename__ = 'UserRoles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))


In my views.py:



from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
role = current_user.role
return str(role)


On the browser, it shows me the returned result:



SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id


Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?



role = current_user.role.name






python flask flask-sqlalchemy flask-login






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 9 at 3:35









D EmmaD Emma

62




62












  • Try user_roles = [role.name for role in current_user.roles]

    – tntxtnt
    Mar 9 at 4:27











  • Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

    – Andrew Allen
    Mar 11 at 16:19

















  • Try user_roles = [role.name for role in current_user.roles]

    – tntxtnt
    Mar 9 at 4:27











  • Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

    – Andrew Allen
    Mar 11 at 16:19
















Try user_roles = [role.name for role in current_user.roles]

– tntxtnt
Mar 9 at 4:27





Try user_roles = [role.name for role in current_user.roles]

– tntxtnt
Mar 9 at 4:27













Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

– Andrew Allen
Mar 11 at 16:19





Can you not do something like Role.query.get(**current users role id**) and add this as an extra column? I'm new too :)

– Andrew Allen
Mar 11 at 16:19












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073739%2fin-python-flask-how-to-get-the-role-name-by-the-current-logged-in-user%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073739%2fin-python-flask-how-to-get-the-role-name-by-the-current-logged-in-user%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page