I’m working on a Flask application where employees can generate class codes. I’ve set up a form to handle the submission of class codes (including a description), but I’m unable to generate the class code. Here’s a summary of the issue:
What’s Happening:
- The form is not submitting correctly when I try to generate the class code.
- I don’t see any error messages, but the class code doesn’t get saved in the database.
- I’ve checked the database, and no new records are being added.
- I’m using Flask-WTF for form handling and Flask-SQLAlchemy for database interactions.
Code:
Route:
@main.route('/employee/dashboard', methods=['GET', 'POST'])
@login_required
def employee_dashboard():
if current_user.role != 'employee':
flash('You must be an employee to access this page.', 'danger')
return redirect(url_for('main.dashboard'))
form = EmployeeForm()
class_codes = ClassCode.query.order_by(ClassCode.created_at.desc()).all()
if form.validate_on_submit():
code = form.code.data
description = form.description.data
# Check for duplicates
if ClassCode.query.filter_by(code=code).first():
flash('Class code already exists!', 'danger')
else:
new_code = ClassCode(code=code, description=description)
db.session.add(new_code)
db.session.commit()
flash('Class code generated successfully!', 'success')
return redirect(url_for('main.employee_dashboard'))
return render_template('employee_dashboard.html', form=form, class_codes=class_codes)
Class Code Model:
class ClassCode(db.Model):
id = db.Column(db.Integer, primary_key=True)
code = db.Column(db.String(50), unique=True, nullable=False)
description = db.Column(db.String(100), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<ClassCode {self.code}>'
Form:
class EmployeeForm(FlaskForm):
code = StringField(
'Class Code',
validators=[DataRequired(), Length(max=20, message="Code must be 20 characters or less.")],
)
description = StringField(
'Description',
validators=[DataRequired(), Length(max=255, message="Description must be 255 characters or less.")],
)
submit = SubmitField('Generate Code')
Question:
- Why is the form not submitting correctly?
- Why is the class code not being saved to the database?
- What might I be missing or what additional debugging steps can I take to troubleshoot this?
Thanks in advance for your help!
What Did You Try?
-
Form Validation:
- I checked if
form.validate_on_submit()
is returningTrue
by adding a debug print statement. It seems like the form isn’t validating properly, but I’m not sure why.
- I checked if
-
CSRF Token:
- I confirmed that the CSRF token is included in the form using
{{ form.hidden_tag() }}
in the HTML.
- I confirmed that the CSRF token is included in the form using
-
Database Query:
- I checked for duplicate class codes using
ClassCode.query.filter_by(code=code).first()
. I also printed the result, and it doesn’t seem to detect duplicates even for existing codes.
- I checked for duplicate class codes using
-
Database Updates:
- I inspected the database, but no new
ClassCode
entries are being added after form submission.
- I inspected the database, but no new
-
Logging Errors:
- I enabled Flask debugging (
app.debug = True
) and looked for errors in the console, but nothing appears to be wrong.
- I enabled Flask debugging (
-
Redirect Behavior:
- I expected the form to redirect back to the dashboard (
return redirect(url_for('main.employee_dashboard'))
) after successfully generating a class code, but the page stays the same and no flash messages are shown.
- I expected the form to redirect back to the dashboard (
What Were You Expecting?
- After filling out the form and clicking the “Generate Code” button, I expected the following:
- The form data (class code and description) would pass validation.
- A new
ClassCode
entry would be saved to the database. - If a duplicate class code exists, I expected a flash message (
'Class code already exists!'
) to appear. - If the class code was saved successfully, I expected to see a success flash message (
'Class code generated successfully!'
) and the new class code displayed in the list below. - The page would refresh with the new class code visible in the list of generated class codes.
yabegitulah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.