I am trying to post a simple html form and pull the data into python/flask. request.form does not appear to be pulling my form data.
I have a function created to pull the variables if the request method is POST, but the URL ends up with the variables being blank. See code below
#app.route('/inquire',methods=['POST','GET'])
def inquire():
if request.method == 'POST':
name = request.form['dname']
email = request.form['demail']
message = request.form['dmessage']
return
redirect(url_for('inquire_success',name=name,email=email,message=message))
return render_template('inquire.html')
#app.route('/inquiresuccess/',methods=['POST','GET'])
def inquire_success(name,email,message):
return render_template('inquiresuccess.html',name=name,email=email,message=message)
the html below :
<div class="container">
<div class="main">
<form method="post" class="form" action="{{
url_for('inquire_success' }}">
<h2>Inquire below and we'll get back to you</h2>
<label>Name :</label>
<input type="text" name="dname" id="dname" value="name">
<label>Email :</label>
<input type="text" name="demail" id="demail" value="email">
<label>Project info :</label>
<textarea class="messagebox" name="dmessage" id="dmessage"
value="message">
</textarea>
<input type="submit" name="submit" id="submit" value=Submit>
</form>
I would like the code to redirect me to inquiresuccess.html with the variables displayed. Thanks for any help.
The form looks to be posting to the wrong endpoint. Try changing
<form method="post" class="form" action="{{ url_for('inquire_success' }}">
to
<form method="post" class="form" action="{{ url_for('inquire' }}">
Related
I am trying to reset password using Django but I am getting the following error:
Method Not Allowed (POST): /reset/done/
Method Not Allowed: /reset/done/
Below are my forms:
Form Which Sent Link To My Email
<form action="{% url 'reset_pass' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" required autofocus>
</div>
<input type="submit" value="Send Email" class="btn btn-primary btn-block">
</form>
Form Which I Get On Clicking That Link
<form action="{% url 'password_reset_complete' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="password" class="form-control" name="new_pass" placeholder="New Password" required autofocus>
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_pass" placeholder="Confirm Password" required>
</div>
<input type="submit" value="Update Password" class="btn btn-primary btn-block">
</form>
URL
path('reset/pass/', views.reset_pass, name='reset_pass'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="feebeeapp/reset_form.html"), name='password_reset_form'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='feebeeapp/login.html'), name='password_reset_complete')
Not sure, what I am doing wrong. Can someone please guide me?
Your form is submitting to the wrong view. You are supposed to make a POST request to a PasswordResetConfirmView view.
If your PasswordResetConfirmView is thus registered as:
path('reset/', auth_views.PasswordResetView.as_view(), name='password_reset')
then in your form you work with:
<form action="{% url 'password_reset' %}" method="post">
…
</form>
Normally you already use this view to render the form. So you submit a POST request to the same view.
This view will send an email with a reset link, and then will redirect to the password_reset_complete view.
I want to select several input files in my flask application, when I want to have an array list of my selected input files, the array is empty. How can I fix that ?
HTML
<form method="POST">
<div class="form-group">
<h6>Select files:</h6> <input type="file" name="inputfiles[]" multiple=""><br><br>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary" >GO</button>
</div>
</form>
Python
#app.route('/gp_bagging_several_apps', methods=['POST','GET'])
def gp_bagging_several_apps():
if request.method == 'POST':
print("HELLO")
f = request.files.getlist("inputfiles[]")
print(f)
I also tried with "inputfiles" instead of "insteadfiles[]". I had the same problem.
Thank you
I think in your input tag, you should have multiple. In your form tag, have action and enctype.
You can try something like below:
<form action="{% url 'function' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="file" name="files" required multiple/></p>
<p><input type="submit" value="Upload" class="btn btn-primary btn-large"/></p>
</form>
And in the function:
if request.method == 'POST':
files = request.FILES.getlist('files')
for file in files:
# process your file
Let me know if it works.
This question already has an answer here:
CSRF token missing or incorrect, even after including the token tag
(1 answer)
Closed 5 years ago.
POST requests to the Django view below result in (403) CSRF verification failed. I've confirmed that the hidden csrf token gets rendered in the page's source. I am also able to make POST requests without errors in other views. I'm unsure how to debug further.
views.py:
def email(request):
if request.method == 'POST':
email = request.POST['email']
fd = open('emaildb.csv','a')
fd.write(email+',somefile\n')
fd.close()
return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'})
else:
return render(request, 'receipts/email.html',)
email.html:
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
U can't call method like that
<form action="email" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
in your urls.py u must write
url(r'^email/$', views.email, name='email')
and call this method using form like that
<form action="{% url 'your_folder_name_where_located_your_urls.py:email'%}" method="post" enctype="text/plain">
{% csrf_token %}
E-mail:<br>
<input type="text" name="email">
<input type="submit" value="Send">
</form>
really struggling with this bad request from flask. I know normally it caused by flask not finding the [key] in the form.. However, I've checked my form and python code 40 times and cannot see any reason that would be the case.. I have commented out each line of the python code that references request.form. I have done it 1 by 1 and I still get a bad request. However when I comment out all the lines the bad request goes away.. Any thought would be wonderful..
Python code;
if request.method == 'POST':
form = 'Add Package Form'
clientId = request.form['id']
date = request.form['date2']
strPrice = request.form['price']
price = float(strPrice)
adultlessons = request.form['adult']
juniorlessons = request.form['junior']
shortlessons = request.form['short']
playinglessons = request.form['playing']
notes = request.form['notes']
form..
<form action="/addpackage" method="post" class="sky-form">
<fieldset>
<section>
<label class="label">Select Package Date</label>
<label class="input">
<i class="icon-append fa fa-calendar"></i>
<input type="text" name="date2" id="date">
</label>
</section>
<div style="margin: -25px"></div>
<fieldset>
<section>
<label class="label">Price</label>
<label class="input">
<input type="text" name="price">
</label>
</section>
<section>
<label class="label">Adult Lessons</label>
<label class="input">
<input type="text" name="adult">
</label>
</section>
<section>
<label class="label">Junior Lessons</label>
<label class="input">
<input type="text" name="junior">
</label>
</section>
<section>
<label class="label">Short Game Lessons</label>
<label class="input">
<input type="text" name="short">
</label>
</section>
<section>
<label class="label">Playing Lessons</label>
<label class="input">
<input type="text" name="playing">
</label>
</section>
<section>
<label class="label">Notes</label>
<label class="textarea textarea-expandable">
<textarea rows="3" name="notes"></textarea>
</label>
<div class="note"><strong>Note:</strong> expands on focus.</div>
</section>
</fieldset>
</fieldset>
<!-- hidden client id -->
<input type="hidden" name="id" value="{{ client.id }}">
<!-- /hidden client id -->
<footer>
<button type="submit" name="addpackage" value="package" class="button">Add Package</button>
</footer>
</form>
This is something of a half-answer, but it was too long for a comment.
If you enable debugging in your Flask app you should get a detailed traceback indicating exactly where the problem is occurring (both in the browser and on your console).
If your application currently has something like:
app.run()
Just set the debug parameter to true:
app.run(debug=True)
If after enabling debugging you're still not sure what's causing the problem, update your question to include the traceback.
For what it's worth, if I dump your form and your code into a simple Flask app, it all seems to work just fine as long as I provide a numeric value for the price field.
Usually you'll get a 400 Bad Request in Flask while submitting a form when you try and access a form key in the request object that doesn't exist.
This is because the request.form object inherits its __getitem__ method the Multidict class in the werkzeug.datastructures module which raises a BadRequestKeyError when a key doesn't exist.
You should give the form data a default value to avoid HTTP 400 error, like this:
default_value = True
is_public = request.form.get('public', default_value)
However, I recommend you to use Flask-WTF.
With Flask-WTF, your code can be simplify to this (an example):
import ...
app = Flask(__name__)
class EditProfileForm(Form):
name = StringField('name', validators=[Length(0, 64)])
location = StringField('city', validators=[Length(0,64)])
website = StringField('website', validators=[Length(0,64), render_kw={"placeholder": "http://..."})
about_me = TextAreaField('Bio', validators=[Length(0,2000)], render_kw={"placeholder": "I'm......"})
submit = SubmitField(u'submit')
#app.route('/edit-profile', methods=['GET', 'POST'])
def edit_profile():
form = EditProfileForm()
if form.validate_on_submit():
current_user.name = form.name.data
current_user.location = form.location.data
current_user.website = form.website.data
current_user.about_me = form.about_me.data
db.session.add(current_user)
flash('Update success!', 'success')
return redirect(url_for('.user', username=current_user.username))
return render_template('edit_profile.html', form=form)
In your html file:
<form method="POST" action="/">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}
{{ form.location.label }} {{ form.location() }}
...
</form>
By the way, if you use Flask-Bootstrap, you can just use one line to render the whole form:
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
I hope it will help.
Being am new to Flask I read the manuals of Flask an Jinja and I know how to read a filed from a template, but not how to update the template.
My template has the following structure which I modified from the doco
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Documet:
<dd><input name=text size = 80 value = {{ AO_sDocument }} > </input >
<dd><input type=submit value=Analyse>
</dl>
</form>
and my Python has the following line
render_template('show_entries.html', AO_sDocument=AO_sDocument )
Yest this line does not seem to update the field.
Thanks!
As Jon Clements points out, your HTML has some markup errors. In order to guarantee all browsers can parse the HTML correctly, your template markup should look more like the following:
<form action="{{ url_for('add_entry') }}" method="post" class="add-entry">
<dl>
<dt>Document:</dt>
<dd><input name="text" size="80" value="{{ AO_sDocument }}" /></dd>
<dd><input type="submit" value="Analyse" /></dd>
</dl>
</form>
Alternately, you may wish to drop the use of <dl> and <dt> in favor of a <label>, which are ever so slightly more semantically correct:
<form action="{{ url_for('add_entry') }}" method="post" class="add-entry">
<label for="text">Document:</label>
<input id="text" name="text" size="80" value="{{ AO_sDocument }}" />
<input type="submit" value="Analyse" />
</form>