I'm working with Flask. I have one route and I want to redirect it to other route when pressing a button, but I want to pass an argument. This is my route:
#app.route('/actualize_product.html', methods=['GET', 'POST'])
def actualize_product():
if request.method == 'POST':
print("post")
query1 = """
SELECT id FROM BD.producto
WHERE id=""" + str(request.form['product_id'])
conection = connect()
resultt = conection.execute(query1)[0]
print(resultt)
return redirect(url_for('/edit_product.html', resultado = resultt)) #Line where I'm redirecting
query = "SELECT * FROM BD.Producto ALLOW FILTERING; "
conection = connect()
result = conection.execute(query)
return render_template('actualize_product.html', products = result)
And this is the route I want it to be redirected
#app.route('/edit_product.html', methods=['GET', 'POST'])
def edit_product():
print("edit")
if request.method == 'POST':
print("Im already here")
return render_template('edit_product.html')
The problem is that the edit_product.html is a file where I use jinja2
<h2>Id del producto: {{resultado.id}} </h2> <br>
<form action="app.py" method="get" onsubmit="return formEsValido()">
<input type= "hidden" value = "{{resultado.id}}" id = "id" name = "id">
<label for="product_name"> Nuevo nombre del Producto: </label>
<input type="text" name="product_name" id="product_name" class="form-control">
<label for="product_price"> Nuevo precio del Producto: </label>
<input type="text" name="product_price" id="product_price" class="form-control">
<label for="descripction"> Nueva descripcion del Producto: </label>
<input type="text" name="description" id="description" class="form-control">
<label for="stock">Nuevo stock del Producto</label>
<input type="text" name="stock" id="stock" class="form-control">
<br>
<button class="btn btn-primary"id="index-buttons" type="submit">Editar Producto</button>
</form>
</div>
If I use render_template instead of redirect, it won't work because after clicking on that button, the route will be /actualize_product.html and I want it to change to /edit_product.html' because I have a form there, I don't know how to pass that variable called "resultado" to jinja2 using redirect.
If all you need is the id, you can pass it as an url parameter.
#app.route('/actualize')
def actualize():
return redirect(url_for('edit', id=123))
#app.route('/edit')
def edit():
id = request.args.get('id')
return render_template('edit.html', id=id)
Related
I have coded the below form and controller but when the page is loaded, the page automatically send request to my database. How to change the form or controller and just send request when I clicked create button.
html code:
<form method="POST" action="/conference/create">
<div class="field">
<div class="control">
<input class="input is-large" type="text" name="name" placeholder="Your Name" autofocus="">
</div>
</div>
<input class="input is-large" type="text" name="shortname" placeholder="Your Shortname">
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-large" type="text" name="year" placeholder="Year">
</div>
</div>
<button class="button is-block is-info is-large is-fullwidth">Create</button>
</form>
</div>
</div>
{% endblock %}
controller function:
#main.route('/conference/create', methods=['POST','GET'])
#login_required
def create_conference():
name = request.form.get('name')
shortname = request.form.get('shortname')
year = request.form.get('year')
startdate = request.form.get('startdate')
enddate = request.form.get('enddate')
submissiondeadline = request.form.get('submissiondeadline')
website = request.form.get('website')
tag = request.form.get('tag')
datem = datetime.today().replace(day=1)
conference = Conference(confid="1", creationdatetime=datem, name=name, shortname=shortname, year=year, startdate=startdate,
enddate=enddate, submissiondeadline=submissiondeadline, creatoruser=12, website=website)
conferenceTag = ConferenceTags("1", tag)
db.session.add(conference)
db.session.commit()
db.session.add(conferenceTag)
db.session.commit()
return render_template('create_conference.html')
By the way, I have changed controller's method parameters with just 'POST' when I do that it gives me not allowed methods error.
you should add an if statement to specify if the incoming request is POST or GET and act accordingly.
if request.method=='GET':
#load page
elif request.method=='POST':
#update database
#main.route('/conference/create', methods=['POST','GET'])
#login_required
def create_conference():
if request.method == 'POST':
name = request.form.get('name')
shortname = request.form.get('shortname')
year = request.form.get('year')
startdate = request.form.get('startdate')
enddate = request.form.get('enddate')
submissiondeadline = request.form.get('submissiondeadline')
website = request.form.get('website')
tag = request.form.get('tag')
datem = datetime.today().replace(day=1)
conference = Conference(confid="1", creationdatetime=datem, name=name, shortname=shortname, year=year, startdate=startdate,
enddate=enddate, submissiondeadline=submissiondeadline, creatoruser=12, website=website)
conferenceTag = ConferenceTags("1", tag)
db.session.add(conference)
db.session.commit()
db.session.add(conferenceTag)
db.session.commit()
return 'you want to do.'
return render_template('create_conference.html')
This question could be duplicate but I have checked all the answers of such related questions and I haven't been able to solve it .
I am trying to get the value from a drop down menu and retrieve certain table from database corresponding to this value .
here is the python file
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="mysql",
database="SugeryClinicDataBase"
)
mycursor = mydb.cursor()
from flask import Flask, redirect, url_for, request,render_template
app = Flask(__name__)
#app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST': ##check if there is post data
Username = request.form['name']
Password = request.form['id']
Selection = request.form['myselectbox']
#value= request.form['']
if Selection==Patient:
mycursor.execute= "SELECT * FROM Patients JOIN DOC_PAT on Patients.id = DOC_PAT.P_code Where Patients.id = PassWord"
myresult = mycursor.fetchall()
for x in myresult:
print(x)
elif Selection==Doctor:
mycursor.execute= "SELECT * FROM Doctors "
myresult = mycursor.fetchall()
for x in myresult:
print(x)
else:
return render_template ('doctors.html')
if __name__ == '__main__':
app.run()
Here is Html file
<!DOCTYPE html>
<form action='' method="POST">
Username:<br>
<input type="text" name="name" value="example">
<br>
Password :<br>
<input type="number" name="id" value="10">
<br>
Selection : <br>
<select name="myselectbox" class="form-control" id="exampleFormControlSelect1" value="">
<br>
<option value="a">choose</option><br>
<option value="b">Patient</option><br>
<option value="c">Doctor</option><br>
<option value="d">Other</option>
</select>
<br> <br>
<input type="submit" value="Submit">
</form>
I am facing this error :
NameError: global name 'Patient' is not defined
Hello I'm trying to send data from a html form into a sqlite database using Flask/SQAlchemy and sqlite. But when I want to test it, I get the following error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'Datum'
But when i look at Datum in my form and in my python file they should be correct? what am I doing wrong?
HTML:
{% block body %}
<form action="{{ url_for('my_form') }}" method="POST">
<div class="container">
<h1>Gasten registratie</h1>
<p>Vul dit formulier in om te registreren</p>
<hr>
<label for="First-Name"><b>Voornaam</b></label>
<input type="text" id="First-Name" placeholder="Vul hier uw voornaam in" name="Voornaam" required>
<label for="Last-Name"><b>Achternaam</b></label>
<input type="text" id="Last-Name" placeholder="Vul hier uw achternaam in" name="Achternaam" required>
<label for="Company-name"><b>Bedrijfsnaam</b></label>
<input type="text" id="Company-name" placeholder="Vul hier uw bedrijfsnaam in" name="Bedrijfsnaam" required>
<label for="Date"><b>Datum</b></label>
<input type="date" id="Date" placeholder="Selecteer de Datum" name="date" required/>
<hr>
<p>In het kader van onze ISAE certificering registreren wij uw gegevens.</p>
<p>Wij verwerken uw gegevens volgends de regels van het AVG.</p>
<button type="submit" class="registerbtn">Registreren</button>
</div>
</form>
{% endblock %}
Python code:
from flask import Flask, render_template, url_for, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///guest.db'
db = SQLAlchemy(app)
class gast(db.Model):
id = db.Column(db.Integer, primary_key=True)
voornaam = db.Column(db.String(15), nullable=False)
achternaam = db.Column(db.String(15), nullable=False)
bedrijfsnaam = db.Column(db.String(50), nullable=False)
datum = db.Column(db.Date)
date_created = db.Column(db.Date, default=datetime.utcnow)
def __repr__(self):
return '<gast %r>' % self.voornaam
#app.route('/')
def index():
return render_template("index.html")
#app.route('/my_form', methods=['POST'])
def my_form():
if request.method == 'POST':
guest_vnaam = request.form['Voornaam']
guest_anaam = request.form['Achternaam']
guest_cnaam = request.form['Bedrijfsnaam']
guest_datum = request.form['Datum']
safe_vnaam = gast(voornaam=guest_vnaam)
safe_anaam = gast(achternaam=guest_anaam)
safe_cnaam = gast(bedrijfsnaam=guest_cnaam)
safe_datum = gast(datum=guest_datum)
try:
db.session.add(safe_vnaam, safe_anaam, safe_cnaam, safe_datum)
db.session.commit()
return redirect('/')
except:
return 'Er ging iets fout met het opslaan van uw gegevens'
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Your date input in your html has a different name to your request.form.
change html input to:
<input type="date" id="Date" placeholder="Selecteer de Datum" name="Datum" required />
Hi I am new and I am attempting to update (or insert using upsert) an item, called "faq" to MongoDB using python (including Jinja templates) and Bootstrap forms with my html. I keep receiving a POST 500 Server Error and just want to be able to successfully update/upsert a document in MongoDB. I am using Mongo 2.6 an python 3.4 - Any help would be greatly appreciated!
My Bootstrap form/ html is as follows:
<form role="form" action="" method="POST">
<div class="form-group">
<label for="category">Category (select one):</label>
<select class="form-control" id="category" name="category">
{% for one in catList %}
<option>{{ one }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="question">Question:</label>
<input type="text" class="form-control" id="question" name="question"/>
</div>
<div class="form-group">
<label for="answer">Answer:</label>
<textarea class="form-control" rows="5" id="answer" name="answer"></textarea>
</div>
<div class="form-group">
<label for="ordinalNum">Ordinal Number</label>
<input type="text" class="form-control" id="ordinalNum" name="ordinalNum">
</div>
<p>This is used to determine the order in which questions are displayed.</p>
<br /><br />
<input type="submit" name="Submit" value="Submit" id="Submit" class="btn btn-primary" />
</form>
My python is as follows:
#app.route('/faqtemp', methods=['GET', 'POST'])
#nocache
def faqtemp():
"""Renders the faqtemp page."""
user = g.user
cat = Category.objects.filter(isDeleted=False)
catList = {}
for thing in cat:
if thing.category not in catList:
catList[thing.category] = thing.ordinalNum
catList = sorted(catList, key=lambda key: catList[key])
links = []
for name in catList:
name = name.replace(" ", "")
links.append(name)
stuff = FAQ.objects.filter(isDeleted=False)
if request.method == 'GET':
return render_template('faqtemp.html',
title='faqtemp',
message='practice',
catList=catList,
stuff=stuff,
user = user,
year = datetime.now().year)
elif request.method == 'POST':
# read form data and save it
category = request.form['category']
question = request.form['question']
answer = request.form['answer']
ordinalNum = request.form['ordinalNum']
aFAQ = FAQ(userUUID=user, category=category, question=question, answer=answer, ordinalNum=ordinalNum)
aFAQ.save()
#FAQ.update(category, question, answer, ordinalNum, user)
return render_template('faqtemp.html',
title='faqtemp',
message='practice',
catList=catList,
stuff=stuff,
user = user,
year = datetime.now().year)
else:
return("<h2>Invalid request</h2>")
And I have created a class Document for an FAQ using python:
from mongoengine import *
import datetime
class FAQ(Document):
question = StringField(required=True)
answer = StringField(required=True)
category = StringField(required=True)
ordinalNum = IntField(required=True)
isDeleted = BooleanField(required=True, default=False)
userUUID = StringField(required=True)
createTS = DateTimeField(required=True, default=None)
def __init__(self, *args, **kwargs):
Document.__init__(self, *args, **kwargs)
if not self.createTS:
self.createTS = datetime.datetime.utcnow()
# def get(self):
def delete(self):
self.isDeleted = True
self.save()
def update(self, category, question, answer, ordinalNum, user):
self.category = category
self.question = question
self.answer = answer
self.ordinalNum = ordinalNum
self.isDeleted = False
self.userUUID = user
self.createTS = datetime.datetime.utcnow()
self.save()
Im not using forms.py to generate my contact area of website, but i want to add captcha in my form.
I try to create only the captcha form in forms.py by doing this:
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
captcha = CaptchaField()
But this do not seems to work.
Any solutiosn?
I'm just using the tag {{ form.as_p}} inside the form
EDIT
This is my view:
def home(request):
if request.method == 'POST':
form = CaptchaTestForm(request.POST)
nome = request.POST.get('nome', None)
assunto = request.POST.get('assunto', None)
email = request.POST.get('email', None)
mensagem = request.POST.get('mensagem', None)
if form.is_valid():
if nome and assunto and email and mensagem:
try:
conteudo = 'Nome: %s\nAssunto: %s\nEmail: %s\nMensagem: %s' % (nome, assunto, email, mensagem.strip())
send_mail('Contato via site Dona Rita', conteudo, EMAIL_HOST_USER,
['contato#witalobenicio.com'], fail_silently=True)
messages.success(request, 'Recebemos o seu contato. Em breve entraremos retornaremos.')
except SMTPException:
messages.error(request, 'Ocorreu um erro ao enviar o e-mail mas já estamos solucionando,\
tente novamente mais tarde.')
else:
messages.error(request, 'Preencha os campos corretamentes.')
slider = Slider.objects.all()
promocoes = Promocao.objects.all()
categorias = Categoria.objects.all()
produtos = Produto.objects.all()
cardapio = {}
for categoria in categorias:
myproducts = []
cardapio[categoria.name] = ''
for produto in produtos:
if produto.category == categoria:
myproducts.append(produto)
cardapio[categoria.name] = myproducts
od = collections.OrderedDict(sorted(cardapio.items()))
return render_to_response('signups.html', {'produtos':od,'promocoes':promocoes, 'slider':slider}, context_instance=RequestContext(request))
And this is my template
<form role="form" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="name">Nome</label>
<input type="text" class="form-control" id="name" placeholder="Seu nome" name="nome">
</div>
<div class="form-group">
<label for="subject">Assunto</label>
<input type="text" class="form-control" id="subject" placeholder="Assunto da Mensagem" name="assunto">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Digite seu email" name="email">
</div>
<div class="form-group">
<label for="message">Mensagem</label>
<textarea class="form-control" rows="3" placeholder="Digite sua Mensagem" id="message" name="mensagem"></textarea>
</div>
{{ form }}
<button type="submit" class="btn btn-default">Enviar</button>
</form>
You are not sending CaptchaTestForm to user when user makes a get request.
To do that, import CaptchaTestForm in your view.
from .forms import CaptchaTestForm
Replace last line of your view with this to send that form.
form = CaptchaTestForm()
return render_to_response('signups.html', {'produtos':od,'promocoes':promocoes,
'slider':slider, 'form': CaptchaTestForm},
context_instance=RequestContext(request))