Problem inserting value into database: Flask SQLAlchemy

Question:

This is the route for the sign-up:

@auth.route('/sign_up', methods=['GET', 'POST'])
def sign_up():
    if request.method == 'POST':
        gender = request.form.get('gender')
        gender_option = Gender.from_str(gender)
        new_user = User(gender=gender_option)

        db.session.add(new_user)
        db.session.commit() 
        return redirect(url_for('auth.my_profile'))   
   
    return render_template("sign_up.html",gender_options = Gender, user=current_user )

This is the structure of the database:

class Gender(enum.Enum):
    not_specified="Not_Specified"
    female="Female"
    male="Male"
    
    @staticmethod
    def from_str(label):
        if label in ('Not_Specified', 'not_specified'):
            return Gender.not_specified
        elif label in ('Male', 'male'):
            return Gender.male
        elif label in ('Female', 'female'):
            return Gender.female
        else:
            raise NotImplementedError


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True)
    gender = db. Column(db.Enum(Gender), nullable = False)

And this is the html I tried:

{% extends "base.html" %} {% block title %}Sign Up{% endblock %} {% block
content %}
<form method="POST">
  <h3 align="center">Sign Up</h3>
    <div class="form-group">
    <label for="gender">Gender</label>
    <select id="gender" name="gender">
    {% for gender in gender_options %}
      <option value="{{gender.value}}">{{gender.value}}</option>
    {% endfor %}
    </select>
  </div>
</form>
{% endblock %}

I get the dropdown populated in the user interface, but the value is not passed down to the database on submit.
Full traceback of the error:

Error on request:
Traceback (most recent call last):
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemysqlsqltypes.py", line 1668, in _object_value_for_elem
    return self._object_lookup[elem]
KeyError: 'female'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packageswerkzeugserving.py", line 319, in run_wsgi
    execute(self.server.app)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packageswerkzeugserving.py", line 306, in execute
    application_iter = app(environ, start_response)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 2095, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 2080, in wsgi_app
    response = self.handle_exception(e)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:UsersmcraciunDocumentsMariaDisertatieWebAppForHotelManagementwebsiteviews.py", line 8, in home
    return render_template("home.html")
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflasktemplating.py", line 147, in render_template
    ctx.app.update_template_context(context)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflaskapp.py", line 756, in update_template_context
    context.update(func())
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflask_loginutils.py", line 392, in _user_context_processor
    return dict(current_user=_get_user())
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflask_loginutils.py", line 359, in _get_user
    current_app.login_manager._load_user()
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflask_loginlogin_manager.py", line 367, in _load_user
    user = self._load_user_from_remember_cookie(cookie)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagesflask_loginlogin_manager.py", line 411, in _load_user_from_remember_cookie
    user = self._user_callback(user_id)
  File "C:UsersmcraciunDocumentsMariaDisertatieWebAppForHotelManagementwebsite__init__.py", line 36, in load_user
    return User.query.get(int(id))
  File "<string>", line 2, in get
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyutildeprecations.py", line 401, in warned
    return fn(*args, **kwargs)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyormquery.py", line 943, in get
    return self._get_impl(ident, loading.load_on_pk_identity)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyormquery.py", line 947, in _get_impl
    return self.session._get_impl(
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyormsession.py", line 2892, in _get_impl
    return db_load_fn(
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyormloading.py", line 541, in load_on_pk_identity        
    return result.one()
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 1408, in one
    return self._only_one_row(
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 559, in _only_one_row
    row = onerow(hard_close=True)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 1272, in _fetchone_impl
    return self._real_result._fetchone_impl(hard_close=hard_close)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 1675, in _fetchone_impl
    row = next(self.iterator, _NO_ROW)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyormloading.py", line 147, in chunks
    fetch = cursor._raw_all_rows()
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 393, in _raw_all_rows
    return [make_row(row) for row in rows]
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyengineresult.py", line 393, in <listcomp>
    return [make_row(row) for row in rows]
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemysqlsqltypes.py", line 1787, in process
    value = self._object_value_for_elem(value)
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemysqlsqltypes.py", line 1670, in _object_value_for_elem   
    util.raise_(
  File "C:UsersmcraciunAppDataLocalProgramsPythonPython310libsite-packagessqlalchemyutilcompat.py", line 207, in raise_
    raise exception
LookupError: 'female' is not among the defined enum values. Enum name: <enum 'Gender'>. Possible values: Not_Specifi.., Female, Male

I can’t figure out what the issue is 🙁 So any support is much appreciated…

Asked By: Maria

||

Answers:

I think what caused me most trouble is that when I tried to debug this issue, I changed the data in my module and I think I didn’t update the database to have my latest changes. After some cleanup and a reset of my database, the issue is now fixed.

The code is now working and this is its current structure:

@auth.route('/sign_up', methods=['GET', 'POST'])
def sign_up():
    if request.method == 'POST':
        gender = request.form.get('gender') 
        new_user = User(gender=gender)
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user, remember = True)
            flash('Account created!', category='success')
            return redirect(url_for('auth.my_profile'))
    return render_template("sign_up.html",gender_options = Gender, user=current_user )

And the database model:

class Gender(enum.Enum):
    Not_specified="Not_Specified"
    Female="Female"
    Male="Male"
    
    @staticmethod
    def from_str(label):
        if label in ('Not_Specified', 'Not_specified'):
            return Gender.not_specified
        elif label in ('Male', 'Male'):
            return Gender.male
        elif label in ('Female', 'Female'):
            return Gender.female
        else:
            raise NotImplementedError
class User(db.Model, UserMixin):
    gender = db. Column(db.Enum(Gender), nullable = False)

And finally, the HTML:

{% extends "base.html" %} {% block title %}Sign Up{% endblock %} {% block
content %}
<form method="POST">
  <h3 align="center">Sign Up</h3>
    <div class="form-group">
    <label for="gender">Gender</label>
    <select id="gender" name="gender">
    {% for gender in gender_options %}
      <option value="{{gender.value}}">{{gender.value}}</option>
    {% endfor %}
    </select>
  </div>
</form>
{% endblock %}
Answered By: Maria
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.