Why is Flask-WTF Form presenting 404 error with POST requests and not GET - post

I have been looking at this for a while, trying to get this form to recognize the POST, and instead it generates a 404 error.
Views
from flask import *
from dockteck.models import EmailForm
from dockteck import app
# Page Routing
#app.route('/')
def main():
return render_template('index.html')
#app.route('/contact', methods=['GET', 'POST'])
def contact():
form = EmailForm()
if request.method == 'POST':
return "Message Sent"
elif request.method == 'GET':
return render_template('contact.html', form=form)
#app.route('/portfolio')
def portfolio():
return render_template('portfolio.html')
I have a simple contact function, that is working fine when a page GET is requested. The following contact page loads for a page GET:
{% extends "template.html" %}
{% block content %}
<h1>Contact Me</h1>
<form action="{{ url_for('contact') }}" method=post>
<div class="row">
<div class="large-4 columns">
{{ form.name.label }}
{{ form.name }}
</div>
<div class="large-4 columns">
{{ form.email.label }}
{{ form.email }}
</div>
<div class="large-4 columns">
<div class="row collapse">
{{ form.subject.label }}
{{ form.subject }}
</div>
</div>
</div>
<div class="row">
<div class="large-12 columns">
{{ form.comment.label }}
{{ form.comment }}
</div>
</div>
<div class="row">
<div class="large-6 columns">
{{ form.submit }}
</div>
</div>
</form>
{% endblock %}
Upon submit of this form, it returns a 404 error page, as it requests contact via POST. Additionally, with firefox dev tool inspection, it shows that the page is posting the correct page /contact, but times out with a 404 error, and gives this additional message:
The character encoding of the HTML document was not declared. The
document will render with garbled text in some browser configurations
if the document contains characters from outside the US-ASCII range.
The character encoding of the page must be declared in the document or
in the transfer protocol.
In the template file, I have tried a few varying declarations, but it doesn't seem to make a difference:
<!DOCTYPE html>
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
Let me know if I'm missing anything that would be helpful to solve this problem.
Edit: Here is EmailForm
from wtforms import Form, TextField, TextAreaField, validators, SubmitField
class EmailForm(Form):
name = TextField('Full Name')
email = TextField('Email Address')
subject = TextField('Subject')
comment = TextAreaField('Comments')
submit = SubmitField('Send message')

try to change these things :
from method=post to method="POST"
from form = EmailForm() to form = EmailForm(request.form)
and tell me if you still have any error

Related

Apitome sidebar disappears when included in a layout

I am using the rspec_api_documentation and apitome gems in a version 5.2 ruby on rails app.
This produces excellent documentation, and has a sidebar (div#sidebar) to allow quick access to the correct part of the documentation. When I choose the
config.layout = "layouts/application.html.erb"
option in the apitome.rb initializer, the documentation is rendered, but the sidebar has disappeared. Looking at the page source, the code for the sidebar is not being rendered, i.e. it is not a css problem, the html is not being put into the layout. To make sure it was not something unusual in my application.html.erb file, I simplified it to this
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%= yield %>
</body>
</html>
This sidebar is very useful, so how do I render it in a layout?
Based on the response to this issue, I was able to solve this.
I created a new layout at app/views/layouts.apidocs.html.erb which rendered apitome/docs/navigation. A simple example would be as follows
# app/views/layouts/apidocs.html.erb
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="sidebar" class="sidebar hidden-print" role="complementary">
<%= render 'apitome/docs/navigation' %>
</div>
</div>
<div class="col-md-8" role="main">
<div class="docs-section">
<%= yield %>
</div>
</div>
</div>
</div>
</body>
</html>
I then configured this layout in the
apitome initialiser.
# config/initializers/apitome
Apitome.setup do |config|
...
config.layout = "layouts/apidocs.html.erb"
end
After some css tinkering, it all looked good.

How to get form data in Java Spark using Thymeleaf template engine?

I've built a simple application and now I'm trying to host attach it to a web server. I'm attempting to have a HTML form (using Thymeleaf) that the user enters their location in as text, and then my server will take and produce a result using that string. So to get started, I'm attempting to make a simple spark application that makes a home page with a "enter your location" form, that then gets the users input and does something with it. I can get the "entryMessage" displayed, as tutorials show, but how to get user data is proving difficult.
However, there is very little documentation on how this can be done with these two framworks. My attempt at what the code should look like is as follows. Note the middle post is just me trying to find ways to get the form data - none proved succesful
ThymeleafTemplateEngine engine = new ThymeleafTemplateEngine();
HashMap<String, String> userLocationMap = new HashMap<>();
get("/home", (request, response) -> {
userLocationMap.put("entryMessage", "Please enter your location");
return new ModelAndView(userLocationMap, "home");
}, engine);
post("/home", (request, response) -> {
System.out.println(request.toString());
//System.out.println(request.body());
//System.out.println(userResponse.location);
//response.redirect("/locationAccepted");
return userLocationMap.get("userLocation");
});
get("/locationAccepted", (request, response) -> {
String location = request.queryParams("userLocation");
return new ModelAndView(userLocationMap, "locationAccepted");
}, engine);
with the following thymeleaf templates
home.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p> <span th:text="${entryMessage}"> default message </span> </p>
<form action="/locationAccepted" method="post">
<input type="text" th:field="userLocation"/>
<div class="button">
<button type="submit">Send your message</button>
</div>
</form>
</body>
</html>
and locationAccepted.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p> <span th:text="${userLocation}"> default message </span> </p>
</form>
</body>
</html>
You have two bugs in your code, both in the HTML form:
In your Java code you're defining the route "/locationAccepted" as GET, but your form method attribute is POST => Change your form to GET.
If you want to get the form's input data it should have a name with value userLocation. th:field isn't translated to name (it's translated to field attribute which I'm not sure what it means).
So your form (after Thymeleaf) should look like this:
<form action="/locationAccepted" method="GET">
<input type="text" name="userLocation"/>
<div class="button">
<button type="submit">Send your message</button>
</div>
</form>
And then request.queryParams("userLocation") will work like you wanted.

Script block is not working in GSP page. Any solution?

I have the script block in GSP page as shown in the code below. But the script block is not responding. Instead of printing hello in the console of the page, I get the error undefined operator $. What can be the reason?
getSpecificQuestion.gsp
<html>
<head>
<script>
$('.index').click(function() {
console.log("hello")
});
</script>
<title> Test </title>
</head>
<body>
<div id="question">
<%= "question = $question"%>
</div>
<div id="indexButtons">
<g:each in="${(1..<11)}" var="i">
<input type="button" class="index" value="${i}"/>
</g:each>
</div>
</body>
</html>
Apparently your gsp did not include any jquery in it so it complained about the missing $
Make sure that you include jquery in your gsp before the your script block. If you are using the resources plugin you can do something like this:
<html>
<head>
<r:require module="jQuery1111"/>
<r:script>
$(function() {
$('.index').click(function() {
console.log("hello")
});
})
</r:script>
<title> Test </title>
</head>
<body>
<div id="question">
<%= "question = $question"%>
</div>
<div id="indexButtons">
<g:each in="${(1..<11)}" var="i">
<input type="button" class="index" value="${i}"/>
</g:each>
</div>
</body>
</html>
Using the tag will render your javascript at the bottom of the page after all the DOM elements have been rendered and ready to be manipulated by the scripts.

How to find all <!--/noindex--> tags using xpath, ruby & webdriver?

xpath = //comment()[contains(.,'noindex')] is working for me in Selenium IDE, but it won't work using ruby & webdriver.
How to find all tags?
I'm trying use code:
result = driver.find_elements(:xpath, "//comment()[contains(.,'noindex')]")
puts result
It returns /var/lib/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/response.rb:52:in `assert_ok': invalid selector: The result of the xpath expression "//comment()[contains(.,'noindex')]" is: [object Comment].
html code
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<body class="siteBody">
<div class="wrapper">
<div class="head">
<div class="headIn">
<div class="middleBlock">
<!--noindex-->
<!--/noindex-->
</div>
</div>
</div>
</div>
<div class="foot">
<div class="footerIn">
<div class="footerBottomLeft">
<div class="counters">
<!--/noindex-->
<!-- /Yandex.Metrika counter -->
<!--/noindex-->
<!--noindex-->
<!--LiveInternet counter-->
<!--/LiveInternet-->
<!--/noindex-->
</div>
</div>
</div>
</div>
</body></html>
The resolution is
result = #driver.find_elements(:xpath, "//*[comment()[contains(.,'noindex')]]").count

Web page displaying as XML in Opera

Opera is displaying my new site as XML and I can't for the life of me figure out why.
Here's what firebug has to say
Server ASP.NET Development Server/10.0.0.0
Date Mon, 08 Nov 2010 22:58:32 GMT
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 2.0
Content-Encoding gzip
Cache-Control private
Content-Type text/html; charset=utf-8
Content-Length 1835
Connection Close
Here's what W3C has to say
Line 3, column 6: application/xhtml+xml is not an appropriate Content-Type for a document whose root element is not in a namespace.
<html>
Line 3, column 6: Unnamespaced element html not allowed in this context. (Suppressing further errors from this subtree.)
<html>
Here's the markup
<!DOCTYPE html>
<html>
<head>
<title>What's happening around you right now! - My App</title>
<meta content="no" http-equiv="imagetoolbar" />
<link rel="search" type="application/opensearchdescription+xml" title="My App" href="/assets/xml/opensearch.xml" />
<link rel="stylesheet" type="text/css" href="/MYREALLYCOOLAPP/Extras/siteMaster.Css/1" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<div id="urban-now-logo">
<span>My App</span>
</div>
</div>
<div id="logindisplay">
<span id="logindisplaywrapper">log in | <a href="/MYREALLYCOOLAPP/modalwindow/selectregion"
title="Change Region" class="RegionWindow">Calgary</a> | about | faq
<span style="padding-left: 20px;"></span>
<form action="/MYREALLYCOOLAPP/search" id="searchForm" method="get">
<input id="search-text" name="q" tabindex="1" type="text" maxlength="80" size="28" placeholder="search..." />
</form>
</span>
</div>
<div id="menucontainer">
<div class="floatleft">
<ul class="menu">
<li><a class="youarehere" href="/MYREALLYCOOLAPP/">Now</a></li>
<li>Coming</li>
<li>Hot</li>
<li>Tags</li>
<li>Users</li>
</ul>
</div>
<div class="floatright">
<ul class="menu">
<li>Add Event</li>
</ul>
</div>
</div>
</div>
<div class="clear">
</div>
<div id="main">
<h2>What's Happening Within The Next 24 Hours!</h2>
<hr />
<div id="innermain">
<div class="twocolumn-left">
<div id='bingMap' class="largeMap">
<noscript>
<img src="http://developer.multimap.com/API/map/1.2/OA10091719904371779?zoomFactor=11&width=550&height=400&lat_1=51.18468&lon_1=-114.497999&lat_2=51.169858&lon_2=-114.32549&lat_3=51.083277&lon_3=-114.203964&lat_4=51.063097&lon_4=-114.092031&lat_5=50.939664&lon_5=-113.973568" />
</noscript>
</div>
</div>
<div class="twocolumn-right">
</div>
</div>
<div id="footer">
<ul id="footernavigation">
<li>© 2010 - My App - All Rights Reserved</li>
<li><span class="colorgreen increasesize-140">■</span> about | <span class="colorgreen increasesize-140">
■</span> faq | <span class="colorgreen increasesize-140">■</span> <a href="/MYREALLYCOOLAPP/about/advertise">
advertise</a> | <span class="colorgreen increasesize-140">■</span> legal</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>
<script type="text/javascript" src="/MYREALLYCOOLAPP/Extras/MYREALLYCOOLAPP.js/1"></script>
<script type="text/javascript">
var zoomLevel = 10
var json_object = [{ "lat": 51.063097, "lon": -114.092031, "title": "Jubilee Auditorium", "desc": "Some great concerts go down here"}];
</script>
<script type="text/javascript" src="/MYREALLYCOOLAPP/Extras/bingmaps.js/1"></script>
</body>
</html>
Basically, when I launch the website in Opera, the top says
This document had no style information.
and then all of my markup is displayed (like xml).
It looks like your server is sending the file as text/html to Firefox, but application/xhtml+xml to Opera.
Opera (10.63) has a firebug-like interface you can check this with. Right click on a page to bring up the context menu, select "Inspect Element". Select the "Network" tab and expand the relevant request line. Then open either "Headers" or "Raw" and it will show you the content-type used to send the page to Opera.
To allow Opera to process the page correctly as application/xhtml+xml, add
xmlns="http://www.w3.org/1999/xhtml"
as an attribute to the html element as LukeH says.
Doesn't your DOCTYPE need to specify the appropriate DTD etc? For example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
And/or do you need to specify a namespace for your <html> element? For example:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

Resources