How do you integrate HTML with Django?


Question

I have an HTML file that has a web page design with a single form, for a user to enter his name. I want to create an six entry array for every submission (to later be filled with information on another page)

Is Django the proper utility to use for this? I would like to have the html design file and the python back end processing as separate files. If so, can anyone point me towards a good place to read about integrating HTML and underlying python codes that process HTML submission forms?

1
2
12/27/2011 10:00:03 PM

Django may be overkill for this. If all you want is a way to link a form to some backend Python code, a micro framework like Flask might be a better choice.

Here is how you do a simple form with Flask:

Create a directory project and inside it, a directory templates

Your template is simple:

{% if name %}
    Hello {{ name }}
{% endif %}
<form method="POST">
<input type="text" name="name" value="Enter your name">
<input type="submit">
</form>

Save that as index.html in the templates subdirectory.

Create a file called go.py in the project directory, and in it copy and paste this:

from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

@app.route('/',methods=['POST','GET'])
def process_form():
    if request.method == 'POST':
       form_input = request.form['name']
       return render_template('index.html',name=form_input)
    else:
       return render_template('index.html')

if __name__ == '__main__':
   app.run(debug=True)

Finally from the project directory, type:

python go.py

Open your browser and go to http://localhost:5000/

8
12/28/2011 8:43:15 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon