前提・実現したいこと
HTMLとJavaScriptで書かれたページから入力された名前(name)と市(city)データを取得し、
データベースに格納した上でwebページに表示しようとしています。
Python + Jinjaといった方が正確かもしれませんが、フォーム(ver.2)からデータを取得したいです。
発生している問題・エラーメッセージ
HTMLで書かれたフォームver.1では
name = request.form['name'] city = request.form['city']
の部分で各・名前(name)と市(city)のフォームからデータを取得できていますが、
JavaScript(Python + Jinja)で書かれたフォーム(ver.2)では各フォームからデータを取得する方法がわからず、
現在のコードを実行すると
NameError: name 'form' is not defined
とエラーが出てしまう状態です。
該当のソースコード
python
1from flask import Flask, flash, render_template, request, redirect, url_for, abort, jsonify 2from flask_sqlalchemy import SQLAlchemy 3import sys 4 5app = Flask(__name__) 6#app.config["SECRET_KEY"] = "sample1203" 7app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/simplewr' 8db = SQLAlchemy(app) 9 10#----------------------------------------------------------------------------# 11# Models. 12#----------------------------------------------------------------------------# 13 14class Todo(db.Model): 15 __tablename__ = 'todos' 16 17 id = db.Column(db.Integer, primary_key=True) 18 name = db.Column(db.String) 19 city = db.Column(db.String(120)) 20 21 def __repr__(self): 22 return f'<Todo {self.id} {self.name} {self.city}>' 23 24db.create_all() 25 26#----------------------------------------------------------------------------# 27# Create 28#----------------------------------------------------------------------------# 29 30@app.route('/todos/create', methods=['POST']) 31def create_todo(): 32 error = False 33 body = {} 34 35 try: 36 name = request.form['name'] 37 city = request.form['city'] 38 todo = Todo(name=name, city=city) 39 40 """ 41 if name == "": 42 flash("write your name", "failed") 43 elif city == "": 44 flash("write your city", "failed") 45 """ 46 47 db.session.add(todo) 48 db.session.commit() 49 body['name'] = todo.name 50 body['city'] = todo.city 51 flash("submitted", "success") 52 except: 53 error = True 54 db.session.rollback() 55 print(sys.exc_info()) 56 finally: 57 db.session.close() 58 if error: 59 abort (400) 60 else: 61 return jsonify(body) 62 63@app.route('/') 64def index(): 65 return render_template('index2.html', data=Todo.query.all(), form=form)
index2.html
html
1<html> 2<head> 3 <title>Todo App</title> 4<style> 5 .hidden{ 6 display: none; 7 } 8</style> 9</head> 10<body> 11 <!-- フォーム ver.1 --> 12 <form method="post" action="/todos/create"> 13 <h3>Simple version form</h3> 14 <h4>name</h4> 15 <input type= "text" name="name" /> 16 <h4>city</h4> 17 <input type= "text" name="city" /> 18 <input type= "submit" value="Create" /> 19 </form> 20 <!-- フォーム ver.2 --> 21 <form method="post" class="form"> 22 <h3 class="form-heading">Different version form<a href="{{ url_for('index') }}" title="Back to homepage"><i class="fa fa-home pull-right"></i></a></h3> 23 <div class="form-group"> 24 <label for="name">name</label> 25 {{ form.name(class_ = 'form-control', autofocus = true) }} 26 </div> 27 <div class="form-group"> 28 <label>city</label> 29 <div class="form-inline"> 30 <div class="form-group"> 31 {{ form.city(class_ = 'form-control', placeholder='City', autofocus = true) }} 32 </div> 33 </div> 34 </div> 35 <input type="submit" value="Submit" class="btn btn-primary btn-lg btn-block"> 36 </form> 37 <div id= "error" class="hidden">Something went wrong!</div> 38 <!-- 表示 --> 39 <ul> 40 {% for d in data %} 41 <li>{{d.name}}</li> 42 <li>{{d.city}}</li> 43 {% endfor %} 44 </ul> 45 <!-- データ取得 --> 46 <script> 47 const nameInput = document.getElementById('name'); 48 const cityInput = document.getElementById('city'); 49 document.getElementById('form').onsubmit = function(e) { 50 e.preventDefault(); 51 const name = nameInput.value; 52 const city = cityInput.value; 53 descInput.value = ''; 54 fetch('/todos/create', { 55 method: 'POST', 56 body: JSON.stringify({ 57 'name': name, 58 'city': city, 59 }), 60 headers: { 61 'Content-Type': 'application/json', 62 } 63 }) 64 .then(response => response.json()) 65 .then(jsonResponse => { 66 console.log('response', jsonResponse); 67 li = document.createElement('li'); 68 li.innerText = name; 69 li.innerText = city; 70 document.getElementById('todos').appendChild(li); 71 document.getElementById('error').className = 'hidden'; 72 }) 73 .catch(function() { 74 document.getElementById('error').className = ''; 75 }) 76 } 77 </script> 78</body> 79</html>
試したこと
HTMLファイルにおいてJavaScriptで書かれたフォームver.2(Python + Jinja)が
どのように表示されるのかブラウザで確認したところ
以下のようになっていました。
しかし、webアプリを起動させていない状態なので
そもそも現在のエラーを解決しないと使えないことがわかりました。
Different version form name {{ form.name(class_ = 'form-control', autofocus = true) }} city {{ form.city(class_ = 'form-control', placeholder='City', autofocus = true) }}
補足情報(FW/ツールのバージョンなど)
Python 3.6.0
Flask 1.1.1
SQLAlchemy 1.3.10
PostgreSQL 11.5
あなたの回答
tips
プレビュー