[Django]CRUDのCreate

/hello/forms.py

from django import forms

class HelloForm(forms.Form):
	name = forms.CharField(label='Name', widget=forms.TextInput(attrs={'class':'form-control'}))
	mail = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class':'form-control'}))
	gender = forms.BooleanField(label='Gender', widget=forms.CheckboxInput(attrs={'class':'form-check'}))
	age = forms.IntegerField(label='Age', widget=forms.NumberInput(attrs={'class':'form-control'}))
	birthday = forms.DateField(label='Birth', widget=forms.DateInput(attrs={'class':'form-control'}))

### create.htmlの作成
/hello/templates/hello/create.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossoorigin="anonymous">
</head>
<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<form action="{% url 'create' %}" method="post">
		{% csrf_token %}
		{{ form.as_p }}
		<input type="submit" value="click" class="btn btn-primary mt-2">
	</form>
</body>
</html>

/hello/templates/hello/index.html

<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<table class="table">
		<tr>
			<th>data</th>
		</tr>
	{% for item in data %}
		<tr>
			<td>{{item}}</td>
		</tr>
	{% endfor %}
	</table>
</body>

/hello/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
from .forms import HelloForm

def index(request):
	data = Friend.objects.all()
	params = {
		'title': 'Hello',
		'data': data,
	}		
	return render(request, 'hello/index.html', params)

# create model
def create(request):
	params = {
		'title': 'Hello',
		'form': HelloForm(),
	}
	if(request.method == 'POST'):
		name = request.POST['name']
		mail = request.POST['mail']
		gender = 'gender' in request.POST
		age = int(request.POST['age'])
		birth = request.POST['birthday']
		friend = Friend(name=name, mail=mail, gender=gender, age=age, birthday=birth)
		friend.save()
		return redirect(to='/hello')
	return render(request, 'hello/create.html', params)

– models.pyで定義しているFriendインスタンスを作成して、インスタンスを保存する
– return redirectでリダイレクト

/hello/urls.py

from django.urls import path
from . import views

urlpatterns = [ 
	path('', views.index, name='index'),
	path('create', views.create, name='create'),
]

流れとしては、create.htmlからcreate.htmlにpostして、modelのインスタンスを使ってsave()してリダイレクトさせる
リダイレクト先で、if request.method == ‘POST’としても同じだろう。