html form 태그에서 데이터 받아오기
form 태그에 action과 method를 추가해준다.
# action = "보낼 URL"
# method = "방법"
<form action="{{ url_for('music_create') }}" method="GET">
input 태그에서 이름을 지정해준다.
<-- input태그 마지막에 name=""형식으로 지정 -->
<form action="{{ url_for('music_create') }}" method="GET">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">유저</label>
<input
type="text"
class="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
name="username"
/>
<div id="emailHelp" class="form-text">
사용자(추천인)의 이름을 넣어주세요.
</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">노래 제목</label>
<input
type="text"
class="form-control"
id="exampleInputPassword1"
name="title"
/>
<div id="emailHelp" class="form-text">좋아하는 노래 제목을 넣어주세요.</div>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">가수</label>
<input
type="text"
class="form-control"
id="exampleInputPassword1"
name="artist"
/>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">앨범 커버URL</label>
<input
type="text"
class="form-control"
id="exampleInputPassword1"
name="image_url"
/>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form>
1번에서 action에 지정해준 url로 루트를 생성한다.
@app.route("/music/create")
def music_create():
requests.args.get(”데이터이름”)으로 input태그에서 보내준 데이터를 받아온다.
@app.route('/music/create')
def music_create():
# form으로 데이터 입력 받기
username_receive = request.args.get("username")
title_receive = request.args.get("title")
artist_receive = request.args.get("artist")
image_receive = request.args.get("image_url")
DB에 저장한다.
import os
from flask_sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =\\
'sqlite:///' + os.path.join(basedir, 'database.db')
db = SQLAlchemy(app)
class Song(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
artist = db.Column(db.String(100), nullable=False)
title = db.Column(db.String(100), nullable=False)
image_url = db.Column(db.String(10000), nullable=False)
def __repr__(self):
return f'{self.username} {self.title} 추천 by {self.username}'
with app.app_context():
db.create_all()
b. db저장
@app.route('/music/create')
def music_create():
# form으로 데이터 입력 받기
username_receive = request.args.get("username")
title_receive = request.args.get("title")
artist_receive = request.args.get("artist")
image_receive = request.args.get("image_url")
# 데이터를 DB에 저장하기
song = Song(username=username_receive, title=title_receive, artist=artist_receive, image_url=image_receive)
db.session.add(song)
db.session.commit()
return render_template('music.html')
db 데이터 html로 전달하기
query.all()
@app.route("/music/")
def render_music():
songs_list = Song.query.all()
return render_template('music.html', data=songs_list)
music.html
<div id="card-list" class="row row-cols-1 row-cols-md-4 g-4 mx-auto w-75 pb-5">
{% for song in data %}
<div class="col">
<div class="card h-100">
<img src="{{ song.image_url }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ song.title }}</h5>
<p class="card-text">{{ song.artist}}</p>
<p class="card-text">추천 by {{ song.username }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
db에서 특정 조건에 맞게 필터링하기
ex) http://127.0.0.1:4000/music/남궁철 → 추천인 남궁철만 출력
테이블.query.filter_by(조건).all()
@app.route('/music/<username>/')
def render_music_filter(username):
# 필터하기
filter_list = Song.query.filter_by(username=username).all()
return render_template('music.html', data=filter_list)
music_create()부분을 redirect()로 수정하여 폼 제출 시 해당 추천인 페이지로 이동하도록 해줍니다.