Form์ ์ฌ์ฉ์์ ์ ๋ ฅ์ ๋ฐ๊ธฐ ์ํ ํ๋๋ ์์ ฏ๋ค์ ๋ฌถ์์ ์๋ฏธ
HTML Form์ ๊ธฐ๋ณธํํ
action : ์๋ submit์ ๋๋ ์๋ ์์ฑํ ๋ด์ฉ์ด ๋์ด๊ฐ url๊ฒฝ๋ก
type="text" : ํ ์คํธ ์ ๋ ฅํ๋ ๊ณณ
type="submit" : ๋ค์ action์ ์ทจํ๋๋ฐ ์ฌ์ฉ๋๋ ๋ฒํผ<form action="๋ฐ์ดํฐ๊ฐ ์ ๋ฌ๋ ์ฃผ์(url)" method="HTTP method ์ค ํ๋"> <input type="text" name="๋ด์ฉ ์ ๋ ฅ๋"/> <button type="submit">ํ์ธ</button> </form>
Django์์๋ ์ด๋ฌํ ํผ์ ๊ตฌ์ฑํ๊ธฐ ์ฝ๊ฒ ์ง์ํด์ค.
app_2th/forms.py
from django import forms
class Write_Form(forms.Form):
# forms.@ : ์ด๋ค ํํ์ ์
๋ ฅ์ ๋ฐ์ ๊ฒ์ธ์ง ์ ์
# label, max_length, widget : ํด๋น ํ๋์ ์์ฑ
first_name = forms.CharField(label="์ด๋ฆ",max_length=50)
last_name = forms.CharField(label="์ฑ",max_length=50)
app_2th/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('person/',views.person,name="person"),
path('write/',views.write,name='write'),
app_2th/views.py
from django.shortcuts import render
from .models import Person
from .forms import *
def write(request):
form = Write_Form() # forms.py ์์ ์ ์ํ ํด๋์ค๋ฅผ ๊ฐ์ฒด๋ก ๋๊ฒจ์ค
# context๋ฅผ render๋ก ๋๊ฒจ์ค ๋, ํญ์ ๋์
๋๋ฆฌํํ์ฌ์ผํจ.
context = {
'form':form
}
return render(request,'write.html',context)
app_2th/templates/write.html
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">์ ์ถ</button>
</form>
์คํ๊ฒฐ๊ณผ
Form์ ์์ฑํ ๋ฐ์ดํฐ๋ฅผ ๋๊ธฐ๋ ค๋ฉด ํด์ฃผ์ด์ผ ํ ๊ฒ.
<form action="{% url โresultโ %}" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">์ ์ถ</button>
</form>
from django.urls import path
from . import views
urlpatterns = [
path('person/',views.person,name="person"),
path('write/',views.write,name='write'),
path('result/,views.result,name='result'), # ์ถ๊ฐ๋ ํญ๋ชฉ
def result(request):
print(request) # <WSGIRequest: POST '/result/'>
print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['L1yF1GyP6kwLvt86YEp4yZxivIN05BPvHRSlZsrob0dE7wnxR3GvPivDySWo7Lr7'],
# 'first_name': ['changwoo'],
# 'last_name': ['choi']}>
form = Write_Form(request.POST)
context = {
'form':form
}
if form.is_valid():
return render(request,'result.html',context)
return HttpResponseRedirect('/write/')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User confirmation</title>
</head>
<body>
<h4>{{ form.first_name.value }}</h4>
<h4>{{ form.last_name.value }}</h4>
</body>
</html>
๊ฒฐ๊ณผ