因此,我尝试添加保存在指定目录中的图像名称,并将其添加到数据库中。但是此错误不断出现。尽管图像一直保存在指定目录中。这是我所有的文件Models.py
class Tickets(db.Model):
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(100),nullable=False)
ticket_text = db.Column(db.Text,nullable=False)
date_posted = db.Column(db.DateTime,nullable=False,default=datetime.utcnow)
status = db.Column(db.String(30), nullable=False)
priority = db.Column(db.String(30), nullable=False)
created_by_id = db.Column(db.Integer, nullable=False)
expert_id = db.Column(db.Integer, db.ForeignKey('users.id'),nullable=False)
project_id = db.Column(db.Integer, db.ForeignKey('projects.id'),nullable=False)
comment = db.relationship('Comment', backref='title', lazy='dynamic')
attach = db.relationship('Attachment', backref='ticket', lazy='dynamic')
class Attachment(db.Model):
id = db.Column(db.Integer, primary_key=True)
file = db.Column(db.String(140))
ticket_id = db.Column(db.Integer, db.ForeignKey('tickets.id'), nullable=False)
routes.py
@app.route('/ticket/<ticket_id>',methods=['GET','POST'])
@login_required
def ticket(ticket_id):
ticket = Tickets.query.get_or_404(ticket_id)
com = Comment.query.filter_by(ticket_id=ticket.id).first()
form = CommentForm()
attachform = AttachForm()
if form.validate_on_submit() and form.body.data:
comment = Comment(body=form.body.data,ticket_id=ticket_id,author = current_user.username)
db.session.add(comment)
db.session.commit()
flash('Your comment has been published.')
return redirect(url_for('ticket', ticket_id=ticket_id))
if attachform.validate_on_submit():
if attachform.file.data:
picture_file = save_file(attachform.file.data)
attachment = Attachment(file=picture_file,ticket_id=ticket_id)
db.session.add(attachment)
ticket.attach = picture_file
db.session.commit()
flash('Your file has been published.')
return redirect(url_for('ticket', ticket_id=ticket_id))
file = url_for('static', filename='files/' + str(ticket.attach))
return render_template('ticket.html', title=ticket.title,file=file ,ticket=ticket,form=form,comment=com,attachform=attachform)
此行出现错误
ticket.attach = picture_file
答案 0 :(得分:0)
当ticket_id
应该为整数(键)时,您将其作为字符串传递:
尝试:
@app.route('/ticket/<int:ticket_id>',methods=['GET','POST'])
@login_required
def ticket(ticket_id):
# or use ticket_id = int(ticket_id)
...
答案 1 :(得分:0)
我认为您应该使用外部联接用Tickets
查询Attachment
。
ticket = db.session.query(Tickets, Attachment).outerjoin(Attachment, Tickets.id == Attachment.tickets_id).get_or_404(ticket_id)
此查询后,您需要像这样访问表。
ticket.Tickets.xxx
ticket.Attachments.xxx
因此,您将附件文件设置为ticket.Attachments
。
ticket.Attachments.tickets_id == tickets_id
ticket.Attachments.file = picture_file
如果ticket.Attachments
为无,
tichet.Attachment = attachment