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 to pick a category provided from the database by using QuerySelectField.
When I submit the form, I get TypeError: object of type 'int' has no len().
The goal was to have different events of various types. Like cafes, Restaurants, etc. I think the problem is at if formupload.validate_on_submit():
The Error
> Traceback (most recent call last):
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask_login/utils.py", line 272, in decorated_view
return func(*args, **kwargs)
File "/Users/abc/PythonProjects/file/website/routes.py", line 150, in post_events
if formupload.validate_on_submit():
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/flask_wtf/form.py", line 100, in validate_on_submit
return self.is_submitted() and self.validate()
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/wtforms/form.py", line 318, in validate
return super(Form, self).validate(extra)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/wtforms/form.py", line 150, in validate
if not field.validate(self, extra):
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/wtforms/fields/core.py", line 226, in validate
stop_validation = self._run_validation_chain(form, chain)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/wtforms/fields/core.py", line 246, in _run_validation_chain
validator(form, self)
File "/Users/abc/.conda/envs/file/lib/python2.7/site-packages/wtforms/validators.py", line 104, in __call__
l = field.data and len(field.data) or 0
TypeError: object of type 'int' has no len()
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(),Length(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)
Some parts of post_event.html
<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' )}}
</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' )}}
</div>
<div class="form-group">
<label for="inputAddress2" style="color: black" >Address</label>
{{ 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>
CodePudding user response:
The problem might be from the fields in your model. You have to use NumberRange for IntergerField instead of using Length which is for a string
Please try
price = IntegerField(label='Price:', validators=[DataRequired(), NumberRange(min=1, max=10)])