Unable to Generate Class Code in Flask App – Form Not Submitting Correctly

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?

  1. Form Validation:

    • I checked if form.validate_on_submit() is returning True by adding a debug print statement. It seems like the form isn’t validating properly, but I’m not sure why.
  2. CSRF Token:

    • I confirmed that the CSRF token is included in the form using {{ form.hidden_tag() }} in the HTML.
  3. 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.
  4. Database Updates:

    • I inspected the database, but no new ClassCode entries are being added after form submission.
  5. Logging Errors:

    • I enabled Flask debugging (app.debug = True) and looked for errors in the console, but nothing appears to be wrong.
  6. 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.

What Were You Expecting?

  • After filling out the form and clicking the “Generate Code” button, I expected the following:
    1. The form data (class code and description) would pass validation.
    2. A new ClassCode entry would be saved to the database.
    3. If a duplicate class code exists, I expected a flash message ('Class code already exists!') to appear.
    4. 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.
    5. The page would refresh with the new class code visible in the list of generated class codes.

New contributor

yabegitulah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật