suleymanduzgun
suleymanduzgun

Reputation: 425

trim() function in Python using Flask

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

Upvotes: 2

Views: 3545

Answers (2)

AJC24
AJC24

Reputation: 3336

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.

Upvotes: 1

Chen A.
Chen A.

Reputation: 11338

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.

Upvotes: 1

Related Questions