I'm doing a presentation of the sample model (Footer.objects.all()) and send the result to the template. deduce the template through the cycle for:
{% for entrie in copyright_obj%}
{{entrie.copyright}}
{% endfor%}
The resulting data are displayed on the screen
but if I do so sample Footer.objects.all()[0], I get a message on the screen error
Exception Type: TypeError
Exception Value:
'Footer' object is not iterable
please tell me how can I print the data in this case?
The statement
Footer.objects.all()[0]
don't have any problem.
The thing is you're using the same template and you're trying to iterate over a single Footer objet.
Related
I am working on a project that allows a user to get a random message from MySQL and have it displayed on a page.
I am creating the query to grab a random row within MySQL using SELECT * FROM messages ORDER BY RAND() LIMIT 1 and have tested it within MySQL and it works. My next step is to have the randomly selected row displayed on the page.
My model is
#classmethod
def random_message(cls):
query = "SELECT * FROM messages ORDER BY RAND() LIMIT 1"
results = connectToMySQL("messages_db").query_db(query)
if results:
temp_message = cls(results[0])
return temp_message
Followed by my controller to display my randomly selected row.
#app.route("/message")
def my_message():
messages = Message.random_message()
return render_template('message.html', messages=messages)
On my webpage, when I select the button I have set up to go to "/message", I run into a new error. The error I get when I attempt to go to the next page is TypeError: 'Message' object is not iterable . Per Pauls comment, I had removed "data" from def random_message(cls, data) and had to remove it from the results line after .query_db(query, data).
This is how I am attempting to grab the info
{% for message in messages %}
<p>{{message.message}}</p>
<p>{{message.creator}}</p>
{% endfor %}
And this is how my table is set up
The messages object that you are generating with the random_message method is probably returning None as it might not be entering the if block. Therefore, when you are trying to iterate over this object with {% for message in messages %}, you are getting the error: 'Message' object is not iterable.
The issue seems to be with the connection to MySQL.
Trying to execute python function in HTML but receiving the following error:
ERROR
jinja2.exceptions.TemplateSyntaxError
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'type'.
CODE
<p>Hi, this is a para {{ type(res) }}</p>
CODE EXPLANATION
It just a para that is receiving res dictionary and displaying here. When I am trying to display the whole dictionary it runs well, when displaying a specific value of dictionary it displays nothing, and when finding the type of variable it shows an error.
You can return it as a variable with flask.
return render_template('template.html',res_type=type(res))
and in HTML:
<p>Out:{{res_type}}</p>
Is there a function like trim() in python?
i use Flask miniframework and it doesn't accept:
selected_student = (request.args.get('student_form')).strip()
its error: AttributeError: 'NoneType' object has no attribute 'strip'
selected_student.replace(" ", "")
its error: AttributeError: 'NoneType' object has no attribute 'replace'
i need a function like trim() without coding a class/subclass or javascript
You're seeing the errors that you are seeing because there is no data being passed from your form to the Flask server. Your use of request is returning a None value type as opposed to a str.
You posted the following HTML mark up for your form:
<form action="/student" method='POST'>
<select name="student_form ">
{% for student in students_list %}
<option value="{{student}}">{{student}}</option>
{% endfor %}
</select>
<input type='submit' value='submit' />
</form>
So therefore you're going to need somewhere for Flask to pick up this data on the server side, for example:
#app.route('/student', methods=['POST'])
def receive_student_form_data:
my_selection = str(request.form.get('student_form')).strip()
print(my_selection)
Just to clarify why I've made my method in this way: I notice that you're using request.args.get() in order to retrieve the value sent by the form. This is incorrect.
request.args is used to retrieve key / value pairs from the URL.
request.form is used to retrieve key / value pairs from a HTML form.
So I'd suggest that you should use request.form.get('student_form') instead. If you really want to be certain that it is being cast as a str when retrieved by your Flask server, then you can cast it as a str as follows:
str(request.form.get('student_form'))
Then, as has been suggested by a few people already, you can use the .strip() method to remove any trailing spaces.
There is a strip() method. The error you get is because you are trying to run it on a NoneType object. You need to run it on a string object.
>>> s = 'some string '
>>> s.strip()
'some string'
There is also replace for strings:
>>> s.replace('some', 'many')
'many string '
The issue you encounter is related to something else. You end with a None object instead of what you are trying to get.
I'm creating an application in Python flask and I'm struggling to encode my links. In my HTML template I'm calling data from JSON and based on a variable from JSON, I want to create a link to another page but the variables that have "space" in them, only take the first word and the link doesn't work as it should.
This is my JSON:
[
{
"team":"AFC Bournemouth"
},
{
"team":"Arsenal"
}
]
And this is my python:
#app.route('/<team>/')
def artist(team):
json_data=open('static/data.json').read()
data= json.loads(json_data)
urllib.quote_plus(data.team)
return render_template("team.html", team=team)
I'm trying to use "urllib.quote_plus" but I get an error
AttributeError: 'list' object has no attribute 'team'
I don't know how to fix it.
And this is my loop in html:
{% for data in results %}
<div class="team">
<p><a href=/{{ data.team }}>{{ data.team }}</a></p>
</div>
{% endfor %}
Before I used "urllib.quote_plus" the link for "Arsenal" worked perfect, but for "AFC Bournemouth" it only took the word "AFC".
That is strange that it is working correctly for "Arsenal". Actually you should iterate over the "data" because it is a list
Example:
#app.route('/<team>/')
def artist(team):
json_data=open('static/data.json').read()
data= json.loads(json_data)
data = [{'team': urllib.quote_plus(team['team'])} for team in data]
return render_template("team.html", results=data)
Another thing is that in render_template you are sending variable team and not results (changed in my example). This way it should be fine and work with your Jinja template.
Edit: changed list comprehension
I am trying to use jinja2 templates. I have custom filter called highlight, that takes string and language name and passes them to pyhments for code highlightning. I am trying to use it like this:
{% filter highlight("python") %}
import sys
def main():
pass
{% endfilter %}
But I get this error:
AttributeError: 'str' object has no attribute 'get_tokens'
Then I tried this:
{% filter highlight "python" %}
It does not work either.
There might be a trick via set block filtering and then pasting it back via {{ ... }}, but this technique is not merged in master source code yet, and seems too hacky for me.
So, is that even possible currently, or I am just doing it wrong?
EDIT: Here is filter:
#jinja2.contextfilter
def highlight(context, code, lang):
print("HIGHLIGHT")
print(code)
return jinja2.Markup(pygments.highlight(code, lexer=lang, formatter='html'))
I am an idiot, that was pygments error. By some mistake, I didn't see that last entry in stacktrace was from there.
You should use:
pygments.highlight(
code,
lexer=pygments.lexers.get_lexer_by_name(lang),
formatter=pygments.formatters.get_formatter_by_name('html')
)
instead of:
pygments.highlight(code, lexer=lang, formatter='html')