https://iridescent-zeal.tistory.com/199
모델 정의
from django.db import models
class Student(models.Model):
studentID = models.IntegerField()
name = models.TextField()
major = models.TextField()
def __str__(self):
return self.studentID
urls.py 정의
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='student'),
path('create/', views.createform, name='student_create'),
]
1. HTML Form 이용하기
index.html에서 데이터를 입력 받아 db에 저장 / http://127.0.0.1:8000/student/ 로 rediection
1) template/student/index.html
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
</head>
<body>
<h1>Django 사용자 입력받기</h1>
<h2>HTML Form 이용하기</h2>
<hr>
<form action="{% url 'student_create' %}" method="POST">
{% csrf_token %}
<div>
<label for="studentID">학번</label>
<input type="text" name="studentID" id="studentID">
</div>
<div>
<label for="name">이름</label>
<input type="text" name="name" id="name">
</div>
<div>
<label for="major">전공</label>
<input type="text" name="major" id="major">
</div>
<br>
<input type="submit" value="제출">
</form>
</body>
2) views.py
입력받은 데이터 = request.POST 개체
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Student
def home(request):
return render(request,'student/index.html')
def createform(request):
if request.method == 'POST':
std = Student()
std.studentID = request.POST['studentID']
std.name = request.POST['name']
std.major = request.POST['major']
std.save()
return redirect('student')
2. Django Form 이용하기
link(http://127.0.0.1:8000/student/create)를 click하면 method가 get방식이므로 django form을 이용한다.
1) template/student/index.html
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
</head>
<body>
<h1>Django 사용자 입력받기</h1>
<h2>Django Form 이용하기</h2>
<hr>
<a href="{% url 'student_create' %}">Django form을 이용한 사용자 입력받기</a>
</body>
</html>
2) student/forms.py
# forms.py
from django import forms
from .models import Student
class StdForm(forms.Form):
studentID = forms.IntegerField()
name = forms.CharField(max_length=30)
major = forms.CharField(max_length=100)
3) template/student/form_create.html
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="제출">
</form>
4) student/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Student
from .forms import StdForm
def home(request):
return render(request,'student/index.html')
def createform(request):
# POST라면 입력한 내용을 form을 이용하여 데이터베이스에 저장
if request.method == 'POST':
form = StdForm(request.POST)
# 유효성 검사
if form.is_valid():
std = Student()
std.studentID = form.cleaned_data['studentID']
std.name = form.cleaned_data['name']
std.major = form.cleaned_data['major']
std.save()
return redirect('student')
# GET이라면 입력값을 받을 수 있는 html을 가져다 줘야함
else:
form = StdForm()
return render(request, 'student/form_create.html', {'form': form})
3. Django modelForm 이용하기
1) student/forms.py
from django import forms
from .models import Student
class StdForm(forms.ModelForm):
class Meta:
model = Student
# fields = '__all__'
fields = ['studentID', 'name', 'major']
2) student/views.py
from django.shortcuts import redirect, render
from .models import Student
from .forms import StdForm
def home(request):
return render(request, 'student/index.html')
def createform(request):
# POST라면 입력한 내용을 form을 이용하여 데이터베이스에 저장
if request.method == 'POST' or request.method == 'FILES':
form = StdForm(request.POST, request.FILES)
# 유효성 검사
if form.is_valid():
form.save()
return redirect('student')
# GET이라면 입력값을 받을 수 있는 html을 가져다 줘야함
else:
form = StdForm()
return render(request, 'student/form_create.html', {'form': form})
'Django11' 카테고리의 다른 글
Django Flash Messages (0) | 2023.04.29 |
---|---|
Django Migrations (0) | 2023.04.28 |
Django Models (0) | 2023.04.28 |
Django 배포 (0) | 2023.04.14 |
Getting Started with Django (0) | 2023.04.08 |
댓글