Reputation: 1751
Couldn't find any question related to this issue. I'm probably doing it the wrong way because I'm sure there must be an easier way to achieve this, but I couldn't figure it out yet.
--> I'm trying to get a Python object from Jinja2 back to Python, so I can access its values back in Python.
So I'm passing an array of users from Python(Flask) to a drop-down in HTML which looks like this:
<div class="form-group">
<label>User:</label>
<select class="form-control" name="user">
{% for user in users %}
<option value="{{ user }}">{{ user.firstname }} {{ user.lastname }}
({{ user.birthdate }})</option>
{% endfor %}
</select>
</div>
This works perfectly and I can select a user in the dropdown. Now I want to access the users user.address attributes back in Python. (of course these attributes are already defined in the user class).
So I have a function like this in Python (Flask) which gets triggered when pressing a button:
@app.route("/display_user", methods=["POST"])
def display_user():
user = request.form["user"]
address = user.address
return render_template("show.html", address=address)
Now I'm getting the following error:
"AttributeError: 'str' object has no attribute 'address'".
I'm getting back the json as a string which looks like this:
{'firstname': 'test','lastname': 'test','birthday': 'test','address': 'test'}
I should now probably create a dict out of this string/json and then access these values with ['address'], but somehow I couldn't figure out how. I tried it with json.dumps() which did not work, still the same error message. Also I figured there must be an easier/better way to achieve this.
Any suggestions? (using Python 3.6.2)
Upvotes: 0
Views: 1007
Reputation: 1751
ok, so I ended up with this solution:
I only returned the ._id and not the whole instance of the user as follows:
Jinja2/HTML:
<option value="{{ user._id }}">{{ user.firstname }} {{ user.lastname}} ({{ user.birthdate }})</option>
Then I just did a new query for the user in my database (I'm using MongoDB) using its _id.
Python 3.6:
user_id = request.form["user"]
user = User.get_by_id(user_id)
And then I could access it's attributes with user.address
and so on. Works fine, but I'm not quite happy with the solution since I need to query the database again.
So if anyone has a different approach, I'm glad to hear it :-)
Upvotes: 1
Reputation: 1052
If you get back json as a string you can use json.loads.
import json
values = json.loads('{"firstname": "test","lastname": "test","birthday": "test","address": "test"}')
print(values["firstname"])
This will output test. Please note that the string you posted is not Json. JSON strings must use double quotes.
Upvotes: 0