Python Forum
Unable to Generate Class Code in Flask App - Form Not Submitting Correctly
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unable to Generate Class Code in Flask App - Form Not Submitting Correctly
#1
Hi, 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:

#python
@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:

python
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:

#python
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')
What I’ve Tried:
1. I added debug lines inside the form submission check, but nothing seems to be happening when I submit the form.
2. I’ve ensured that the CSRF token is included in the form ({{ form.hidden_tag() }}).
3. I’ve checked the database for any changes, but no new ClassCode entries are being saved.

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!
Reply
#2
The most common causes for the form not submitting or adding data to the database are related to how the form is rendered and posted in the template(the html code you do show),
missing method="post" in the HTML <form> tag, CSRF issues, or silent form validation failures.
Make sure that the HTML form is correctly set up with method="post".
{{ form.hidden_tag() }} included so the CSRF token is properly sent.
Also, print out form.errors to identify any hidden validation issues.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help me in flask code iiiiiiiiii 1 845 Sep-03-2024, 06:53 AM
Last Post: ahmad_296
  Flask: editing a submitted form test 1 2,458 Jun-07-2022, 10:37 AM
Last Post: test
  Flask Basics request.form ifigazsi 0 2,394 Feb-09-2021, 09:05 AM
Last Post: ifigazsi
  Flask request.form ifigazsi 2 6,069 Feb-02-2021, 11:56 AM
Last Post: buran
  How do I use shortcut to import class in VS code? cheers100 0 2,059 Nov-28-2020, 08:11 AM
Last Post: cheers100
  Unable to scrape more than one URL with this code SamLearnsPython 2 2,544 Nov-19-2020, 07:08 PM
Last Post: SamLearnsPython
  [FLASK] How to structure the code in my case ? Fre3k 4 3,489 May-04-2020, 04:43 PM
Last Post: Fre3k
  got some problem with flask signup form. darktitan 1 2,728 Aug-30-2019, 06:05 AM
Last Post: aligoren
  how i save the html form to flask database mebaysan 1 8,110 Feb-07-2019, 12:56 AM
Last Post: snippsat
  Flask return http status code 200 but web browser not recive supernoobs 2 15,167 Dec-29-2018, 09:27 PM
Last Post: Unisoftdev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020