Index ソフト・ハード Djangoタスク | FunctionViewサンプル |
project01 topic_create index |
project01 topic_create
from . forms import TopicForm # ,TopicModelForm (TopicForm を使用)
def topic_create(request):
template_name = 'thread/create_topic.html'
ctx = {}
if request.method == 'GET':
form = TopicForm()
ctx['form'] = form
return render(request, template_name, ctx)
if request.method == 'POST':
topic_form = TopicForm(request.POST)
if topic_form.is_valid(): # is_valid()関数呼び出し
# topic_form.save()
topic = Topic()
cleaned_data = topic_form.cleaned_data
# cleaned_dataから検証済みのデータを取り出し
topic.title = cleaned_data['title']
topic.message = cleaned_data['message']
topic.user_name = cleaned_data['user_name']
topic.category = cleaned_data['category']
# Modelのオブジェクトに値をセット
topic.save() # オブジェクトのsave()関数を呼び出し保存
return redirect(reverse_lazy('base:top'))
else:
ctx['form'] = topic_form
return render(request, template_name, ctx)
index
from django.shortcuts import render
def index(request):
if request.method == "GET":
params = {"message":"View関数:Get処理"}
return render(request,"Index.html",params)
if request.method == "POST":
params = {"message":"View関数:Post処理"}
return render(request,"Index.html",params)
・参考・例、テンプレートに変数を渡す。
def viewFunction(request):
templateName = "template.html"
context = {"variable" : "hello world!"}
# 辞書(context)の中のキー(variable)の値がテンプレート内での変数名
return render(request,templateName,context)
・例、変数の展開
def viewFunction(request):
templateName = "template.html"
templateText = "Hello World!"
context = {"text" : template_text}
# "text"がテンプレート内での変数名
return render(request,template_name,context)
# 変数の入った辞書を第三引数にする。
|
All Rights Reserved. Copyright (C) ITCL |