
前置准备
建立一个新的专案目录 week11,并且启动虚拟环境
cd C:\django_projects mkdir week11 cd week11 python -m venv env .\env\Scripts\activate.bat
下载并将 week4 的成果放到 week11 目录底下,点我下载
接着安装 django
pip install django

启动 django 伺服器并且测试功能是否正常,帐密为
- 帐号: admin
- 密码: 123456
cd mysite python manage.py runserver


简单表单 Hello World
开启 VSCODE
code .
在 polls 底下建立一个档案 forms.py,并且贴上以下的程式码
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
编辑 polls/views.py 档案,覆蓋以下程式码
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
from .forms import NameForm
""" def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list,}
return render(request, 'polls/index.html',context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
"""
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/polls/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))在 polls/templates 底下建立一个档案 name.html,并且贴上以下程式码
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>编辑 urls.py 档案,覆蓋以下程式码
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('your-name/', views.get_name, name='get_name'),
]启动伺服器,进入 http://127.0.0.1:8000/polls/your-name/ 查看
python manege.py runserver
输入随意名称按下 Submit 按钮,会回到 polls/ 页面底下
表单进阶练习 – 联络人
修改 forms.py 档案,覆蓋成以下程式码
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)修改 views.py 档案,覆蓋成以下程式码
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
from .forms import NameForm, ContactForm
""" def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list,}
return render(request, 'polls/index.html',context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
"""
def process_contact_form(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
return render(request, 'contact_result.html', {'subject': subject,
'message':message, 'sender':sender, 'cc_myself':cc_myself})
# if a GET (or any other method) we'll create a blank form
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/polls/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))在 polls/templates 底下新增一个档案 contact_form.html ,并且贴上以下程式码
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>在 polls/templates 底下新增一个档案 contact_form_result.html,并且贴上以下程式码
<h1>Your Input is:</h1>
<h4>{{ subject }}</h4>
<h4>{{ message }}</h4>
<h4>{{ sender }}</h4>
<h4>{{ cc_myself }}</h4>修改 polls/urls.py 档案,覆蓋以下程式码
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('your-name/', views.get_name, name='get_name'),
path('process_contact_form/', views.process_contact_form,name='process_contact_form')
]
开启网址 http://127.0.0.1:8000/polls/process_contact_form/ 测试
依序填入资讯并且按下 Submit
使用模组建立表单
参考文章: 官方 Document
修改 polls/forms.py 档案,覆蓋以下程式码
from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Question
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ['question_text', 'pub_date']修改 polls/views.py 档案,覆蓋以下程式码
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
from .forms import NameForm, ContactForm, QuestionForm
""" def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list,}
return render(request, 'polls/index.html',context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
"""
def create_question(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/polls/')
else:
form = QuestionForm()
return render(request, 'question_form.html', {'form': form})
def process_contact_form(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
return render(request, 'contact_result.html', {'subject': subject,
'message':message, 'sender':sender, 'cc_myself':cc_myself})
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))在 polls/templates 底下建立一个档案 question_form.html ,并且贴上以下程式码
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>修改 polls/urls.py 档案,并且覆蓋以下程式码
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('your-name/', views.get_name, name='get_name'),
path('process_contact_form/', views.process_contact_form,name='process_contact_form'),
path('create_question', views.create_question, name='create_question')
]开启网址 http://127.0.0.1:8000/polls/create_question,并且填入资料
按下 Submit 按钮,可以看到已经新增了一个问题
- 受保护的内容: NAS 版 Mathbot 管理网站与 Linebot 启动方法 - 2024 年 11 月 15 日
- Realtime 啥鬼的 - 2021 年 6 月 15 日
- nodejs 数学游戏 - 2021 年 6 月 8 日















在〈week11 表单建立以及操作〉中有 1 则留言