Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python I need help with Flask Form Submission Page

niiakoadjei

New Coder
# when I fill the form on the HTML Page (newfile.html) and click the SUBMITButton, NOTHING HAPPENS (No Saving file to database, and NO REDIRECT).
# I need assistance because I'm a beginner and don't know if the problem is with my code or the IDE because the same code was working previously.
# Attached are the HTML codes


Python:
[CODE=python][CODE=python]# ===== IMPORT ALL DEPENDENCIES ===== #

from flask import Flask, render_template, request, redirect, url_for, flash, send_file, send_from_directory

from flask_wtf import FlaskForm

import os

from wtforms import StringField, PasswordField, SubmitField, SelectField

from wtforms.validators import DataRequired, EqualTo

from wtforms.fields.html5 import DateField

from flask_login.utils import login_required

from flask_sqlalchemy import SQLAlchemy

from datetime import datetime, date

from werkzeug.utils import secure_filename

from werkzeug.security import generate_password_hash,check_password_hash

#from wtforms.widgets import TextArea

from flask_login import UserMixin, login_user, logout_user, LoginManager, current_user



app = Flask(__name__)

app.debug = True

UPLOAD_FOLDER = 'D:/PROJECTS/DocTrack/uploads'

# ===ADD DATABASE===

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///doctrack.db'

app.config['SECRET_KEY'] = 'sdkmlmlmsajk573088#__=5e'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}



db = SQLAlchemy(app)



# =====WE CREATE A DATABASE MODEL FOR FILES=====

class Files(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    reference = db.Column(db.String(200), nullable=False)

    title = db.Column(db.String(200), nullable=False)

    description = db.Column(db.String(200), nullable=False)

    source = db.Column(db.String(200), nullable=False)

    status = db.Column(db.String(200), nullable=False)

    destination = db.Column(db.String(200))

    attachment = db.Column(db.String(200), nullable=False)

    date_received = db.Column(db.DateTime, nullable=False)

    

    

# ===CREATE FORM FOR DOCUMENT ENTRY===

class FileForm(FlaskForm):

    reference = StringField("Letter Reference", validators=[DataRequired(message='Enter Document Reference')])

    title = StringField("Title", validators=[DataRequired(message='Enter Document Title')])

    description = StringField("Description", validators=[DataRequired(message='Enter Document Description')])

    source = StringField("Received From", validators=[DataRequired(message='Enter Document Description')])

    status = SelectField("Status", choices=['Seen','Pending','Approved', 'Not Approved'], validators=[DataRequired()])

    destination = StringField("Destination", default='Not Forwarded')

    date_received = DateField("Received Date", format='%d-%m-%Y', validators=[DataRequired()])

    #file = FileField(label='Upload File', validators=[FileAllowed(['.jpg', '.jpeg', '.png', '.pdf', '.docx'])])

    submit = SubmitField("Submit")





@app.route('/')

@app.route('/home')

def home():

    return render_template('home.html')



def allowed_file(filename):

    return '.' in filename and \

           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS



# =====ROUTE FOR FILE ENTRY=======

@app.route('/new-file', methods=['GET', 'POST'])

@login_required

def new_file():



    form = FileForm()

    if form.validate_on_submit():

        filename = ""

        # check if the post request has the file part

        file = request.files['file']

        # If the user does not select a file, the browser submits an

        # empty file without a filename.

        if file.filename == '':

            flash('No selected file')

            return redirect(request.url)

        if file and allowed_file(file.filename):

            filename = secure_filename(file.filename)

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))



            poster = current_user.id

            post = Files(reference=form.reference.data,

                         title=form.title.data,

                         description=form.description.data,

                         source=form.source.data,

                         status=form.status.data,

                         destination=form.destination.data,

                         attachment=filename,

                         date_received=form.date_received.data,

                         poster_id=poster)

            # ===WE CLEAR THE FORM===

            form.reference.data = ""

            form.title.data = ""

            form.description.data = ""

            form.source.data = ""

            form.status.data = ""

            form.destination.data = ""

            form.date_received.data = ""



            # ===WE ADD THE FORM INPUTS TO THE DATABASE===

            db.session.add(post)

            db.session.commit()



            flash("Document Filed successfully!")



            return redirect('files.html')

        return render_template('newfile.html', filename=filename, form=form)

    return render_template('newfile.html', form=form)


# ====CREATE A ROUTE(PAGE) TO DISPLAY ALL FILED DOCUMENTS======
@app.route('/files',methods=['GET', 'POST'])
@login_required
def files():
        # ===GET ALL POSTS FROM DATABASE===
    files = Files.query.order_by(Files.date_received.desc())
    return render_template('files.html', files=files)
[/CODE][/CODE]
 

Attachments

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom