简体   繁体   中英

FLASK PYTHON: Submitting a flask form not working

I am trying to make an upload form with Flask where the user needs to fill in the information needed, upload a photo, and also pick a category provided from the database by using QuerySelectField.

When I submit the form, nothing happens. It redirects me to the same page and the database is empty.

form.py

class UploadForm(FlaskForm):
title = StringField(label='Title:', validators=[DataRequired(), Length(min=2, max=30)])
organizer = StringField(label='Name:', validators=[DataRequired(), Length(min=2, max=30)],
                        render_kw={'readonly': True})
type = QuerySelectField(query_factory=choice_query, allow_blank=False, get_label='name')
description = StringField(label='description',validators=[DataRequired(), Length(min=1, max=250)])
address = StringField(label='address',validators=[DataRequired(), Length(min=1, max=50)])
file = FileField(label='file', validators=[DataRequired()])
price = IntegerField(label='Price:', validators=[DataRequired(), NumberRange(min=1, max=10)])
upload = SubmitField(label='Post')

model.py

class Event(db.Model):
__tablename__ = "event"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(30), nullable=False)
price = db.Column(db.Integer(), nullable=False)
location = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(1024), nullable=True, unique=True)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
type = db.Column(db.Integer(), db.ForeignKey('category.id'), nullable=False)
image_file = db.Column(db.String(20), nullable=True, default='default.jpg')
owner = db.Column(db.Integer(), db.ForeignKey('eventowners.id'), nullable=False)
reserver = db.relationship('Reservation', foreign_keys=[Reservation.reserved_id],
                           backref=db.backref('reserved', lazy='joined'), lazy='dynamic',
                           cascade='all, delete-orphan')



class Choice(db.Model):
__tablename__ = "category"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False)
event = db.relationship('Event', backref='events', lazy=True)

def __repr__(self):
    return '[Choice {}]'.format(self.name)

class EventOwner(db.Model, UserMixin, USER):
__tablename__ = 'eventowners'
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
sub_type = db.Column(db.String, nullable=True, default=00)
events = db.relationship('Event', backref='eventowner', lazy=True)
follower = db.relationship('Follow', foreign_keys=[Follow.followed_id],
                           backref=db.backref('followed', lazy='joined'), lazy='dynamic',
                           cascade='all, delete-orphan')

routes.py

@app.route('/event/new', methods=['GET', 'POST'])
@login_required
def post_events():
    if not os.path.exists('static/' + str(session.get('id'))):
       os.makedirs('static/' + str(session.get('id')))
    file_url = os.listdir('static/' + str(session.get('id')))
    file_url = [str(session.get('id')) + "/" +
                 file for file in file_url]
    formupload = UploadForm()
    eventowner = current_user.id
    formupload.organizer.data = eventowner
    event = Event(owner=formupload.organizer.data)
    if formupload.validate_on_submit():
       event = Event(title=formupload.title.data,
                  type=formupload.type.data,
                  description=formupload.description.data,
                  price=formupload.price.data,
                  location=formupload.address.data,
                  image_file=photos.save(formupload.file.data,
                                         name=str(session.get('id')) + '.jpg',))

      db.session.add(event)
      db.session.commit()
      flash('Event Posted!')
      return redirect(url_for('events_page'))
    return render_template('post_event.html', formupload=formupload, event=event)

@app.route('/event', methods=['GET', 'POST'])
def events_page():
    event = Event.query.order_by(Event.date_posted.desc()).all()
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Event.query
    pagination = Event.query.order_by(Event.date_posted.desc()).paginate(page,
                                                                         per_page=
                                                                         current_app.config['FLASKY_POSTS_PER_PAGE'],
                                                                         error_out=False
                                                                         )
    events = pagination.items
    return render_template('event.html', events=events, pagination=pagination, show_followed=show_followed, event=event)

post_event.html

    {% extends "base.html" %}
{% block content %}
  <div class="breadcrumbs">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-6 col-md-6 col-12">
                    <div class="breadcrumbs-content">
                        <h1 class="page-title">Events</h1>
                    </div>
                </div>
                <div class="col-lg-6 col-md-6 col-12">
                    <ul class="breadcrumb-nav">
                        <li><a href="/">Home</a></li>
                        <li>Events</li>
                    </ul>
                </div>
            </div>
        </div>
  </div>

<form method="post" enctype="multipart/form-data" action="">
   {{ form.hidden_tag() }}
  <div class="search-form wow fadeInUp" data-wow-delay=".7s" style="background: none; margin-top:50px; margin-bottom:50px">

    <div class="form-group">
      <label for="Title" style="color: black" >Event Title</label>
      {{ formupload.label }} {{ formupload.title(class='form-control' )}}
    </div>

    <div class="form-group col-md-6">
      <label for="organizer" style="color: black" >Organizer</label>
     <!-- <input type="text" class="form-control" id="Organizer"> -->

      <div> {{ formupload.label }}  </div>
      <div> {{ formupload.organizer._value()}}</div>

    </div>
    <div class="form-group col-md-4">
      <label for="inputState" style="color: black" >Type</label>
          {{ formupload.csrf_token }}
          {{ formupload.type }}
          <ul>
            {% for error in formupload.type.errors %}
            <li style="color:red;">{{ error }}</li>
            {% endfor %}
          </ul>
    </div>
    <div class="form-group col-md-6">
      <label for="description" style="color: black" >Description</label>
      {{ formupload.label }} {{ formupload.description(class='form-control' )}}
      <!--<input type="text" class="form-control" id="desc"> -->
    </div>
    <div class="form-group col-md-6">
      <label for="starting_price" style="color: black" >Starting Price</label>
      {{ formupload.label }} {{ formupload.price(class='form-control' )}}
      <!-- <input type="text" class="form-control" id="Price"> -->
    </div>
      <div class="form-group">
        <label for="inputAddress2" style="color: black" >Address</label>
       <!-- <input type="text" class="form-control" id="Address" placeholder="Corso Duca degli Abruzzi, 24"> -->
        {{ formupload.label }} {{ formupload.address(class='form-control' )}}
     </div>
    <div class="form-group">
       <div class="form-check">
         <input class="form-check-input" type="checkbox" id="gridCheck">
         <label class="form-check-label" for="gridCheck" style="color: black">
          I agree to the Terms of Service and Privacy Policy
          </label>
        </div>
    </div>
    <div class="form-group">
        {{ formupload.file.label }}
        {{ formupload.file }}
        {{ formupload.upload }}
        {% for file in filelist %}
            <img class="upload-img"  src='{{ url_for("static",filename=file) }}' alt="">
        {% endfor %}
    </div>

    <div class="form-group">
        {{ form.submit(class="btn btn--primary") }}
    </div>

  </div>
</form>

  {% include "bottom.html" %}

<script src="{{ url_for('static',filename='js/bootstrap.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/wow.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/tiny-slider.js') }}"></script>
<script src="{{ url_for('static',filename='js/glightbox.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/main.js') }}"></script>

{% endblock %}

Unless you're submitting a form via Javascript, a form submission will get sent to the value in action attribute of the form. Yours is blank which is why the page is simply reloaded.

<form method="post" enctype="multipart/form-data" action="">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM