I'm trying to create a website using Flask and Materialize. Unfortunately, when I try using Materialize's button's class the form action doesn't work. All attempts I have made to get it to work end up changing the style of the image I want to use. Is this just not possible, or am I missing something?
Here is the application code:
@application.route("/test",methods=['GET', 'POST'])
def test():
if request.method =='POST':
print("It worked")
return render_template("test.html", the_title="Test")
And here is the HTML page:
{% extends 'main.html' %}
{% block body %}
<form action="{{ url_for('test') }}" method="post">
<!--This works-->
<button name="test1" type="submit">Test1</button>
<!--This doesn't work-->
<a class="btn-large light-blue lighten-1"><Test2</a>
</form>
{% endblock %}
The first issue is a small typo -- an extra <
before the link text. It should be:
<a class="btn-large light-blue lighten-1">Test2</a>
Even then, the link isn't really going to do much. You would need a href
attribute for the link to actually point to something. For example:
<a href="/test" class="btn-large light-blue lighten-1">Test2</a>
Even then, this would make a GET
request to the /test
route rather than submit the form.
I suggest reading up on the Materialize documentation for buttons here:
When you use a button to submit a form, instead of using a input tag, use a button tag with a type submit
So when you want to submit a form, you should be using a regular button
instead of an a
(hyperlink) tag. Using the same Materialize classes, the button and link would look identical.
You could use an a
tag to submit the form, if that's what you really want -- you just need to add some JavaScript to add an event listener, listening to the click
event and your handler can then submit the form.
Here is an example, demonstrating the various possibilities.
button
is a regular HTML button that will submit the formbutton
also submits the form, but applies Materialize stylingGET
request, rather than submit the formdocument.getElementById('link2').addEventListener('click', (e) => {
e.currentTarget.parentNode.submit();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<form action="{{ url_for('test') }}" method="POST">
<!-- This is a plain HTML button -->
<button type="submit" id="btn1">Test1</button>
<!-- This is a materialize button -->
<button class="btn-large light-blue lighten-1" type="submit" id="btn2">Test2</button>
<!-- These are links with materialize style -->
<a class="btn-large light-blue lighten-1" id="link1" href="/test">Test3</a>
<a class="btn-large light-blue lighten-1" id="link2">Test4</a>
</form>