I am building a web chat application with chat rooms. I have a page where users can open a new room, inside the page, there is a form. I want to display a message to the user if he submits the form with a room that already exists.
For example: Room 456 already exists and the user tried to open 456 room. so I want to pop up a message that the room already exists.
The server side
@app.route('/NewRoom')
def newRm():
return render_template('NewRoom.html')
@app.route('/chat',methods=['GET','POST'])
def CreateRm():
if(request.method=='POST'):
username = request.form['username'].lower()
room = request.form['room'].lower()
ExistRoom = DBManage.ExistRoom(room)
error = "YOU ENTERED ROOM THAT ALREADY EXISTS"
if not ExistRoom:
limit = request.form['limit']
if limit == '':
limit = 'UNLIMITED'
session['limit'] = limit
image = request.files['getFile']
newImgs = open("static/images/" username ".jpg","wb")
newImgs.write(image.read())
newImgs.close()
room = room[:5].strip()
DBManage.newRoom(room,limit)
DBManage.newPerson(username,room)
#sDBManage.RoomUsers(room)
#Store the data in session
session['username'] = username
session['room'] = room
return render_template('chat.html', session = session)
else:
flash(error)
return redirect(url_for('newRm',error=error))
Inside CreateRm function the else at the end didn't work for me well, it's refreshing the page but doesn't send the error message, not really know how to solve that.
Client side
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}
{% endif %}
Thanks all.
CodePudding user response:
The problem is that you are returning a redirect to another route as well as trying to pass a variable to a template in that route. One way you could do this is by simply re-rendering the template, passing the variable, error
to it at the same time. Try replacing:
return redirect(url_for('newRm',error=error))
with
return render_template('NewRoom.html', error=error)
Another option would be configuring your newRm
route to accept optional arguments. This could look something like this:
@app.route('/NewRoom', defaults={'error':''})
@app.route('/Newroom/<error>')
def newRm():
return render_template('NewRoom.html')
You then pass an error to this route exactly as you have been doing.
return redirect(url_for('newRm', error=error))
To completely solve your problem, you'll also have to add a return
statement outside your if(request.method=='POST'):
to catch any GET requests. It could be something like this:
return render_template('NewRoom.html')