Python Lover(3)Django Doc - POST FORM and Testing
1. Form
How the POST Form Working
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
We have the csrf_token to handle the security issue.
The Result Page
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
The Action-View
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from polls.models import Question, Choice
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You did not select a choice.",
})
else:
selected_choice.votes +=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Use Generic Views: Less Code
I do not like it, I want more control of the codes.
https://docs.djangoproject.com/en/1.7/intro/tutorial04/
2. Automated Testing
2.1 Try to Creating Test Class
Find the file easypoll/polls/tests.py
import datetime
from django.test import TestCase
from django.utils import timezone
from polls.models import Question
# Create your tests here.
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is in the future
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertEqual(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is older than 1 day
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() should return True for questions whose
pub_date is within the last day
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(), True)
It is easy to run the Tests
>python manage.py test polls
Creating test database for alias 'default'... . ---------------------------------------------------------------------- Ran 1 test in 0.001s
2.2 Test a View
The Django Test Client
We can use it even from the Console, that is amazing.
>python manage.py shell
Prepare the Context, then we can parse the response or something like that from my understanding.
>>> from django.test.utils import setup_test_environment >>> setup_test_environment()
Set up the Client
>>> from django.test import Client >>> client = Client()
Using the client to talk to Our Server
>>> response = client.get('/') >>> response.status_code 404
Reverse the URL from Server Conf
>>> from django.core.urlresolvers import reverse >>> response = client.get(reverse('polls:index')) >>> response.status_code 200
>>> response.content b'\n <ul>\n \n <li><a href="/polls/2/">National</a></li>\n \n <li><a href="/polls/1/">what's up?</a></li>\n \n </ul>\n'
Directly hit the URL
>>> response = client.get('/polls/') >>> response.content b'\n <ul>\n \n <li><a href="/polls/2/">National</a></li>\n \n <li><a href="/polls/1/">what's up?</a></li>\n \n </ul>\n'
Directly check the context, that is really amazing and you do not need to have your app running.
>>> response.context['latest_question_list'] [<Question: National 2014-09-15 19:23:15+00:00>, <Question: what's up? 2014-09-15 17:25:50+00:00>]
Not from the Shell, Write in tests.py
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from polls.models import Question
#public static method?
def create_question(question_text, days):
"""
Creates a question with the given `question_text` published the given
number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text,
pub_date=time)
Test Classes
class QuestionViewTests(TestCase):
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_a_past_question(self):
"""
Questions with a pub_date in the past should be displayed on the
index page
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_a_future_question(self):
"""
Questions with a pub_date in the future should not be displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
#print(response.content)
self.assertContains(response, "No polls are available.",
status_code=200)
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
should be displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class QuestionIndexDetailTests(TestCase):
def test_detail_view_with_a_future_question(self):
"""
The detail view of a question with a pub_date in the future should
return a 404 not found.
"""
future_question = create_question(question_text='Future question.',
days=5)
response = self.client.get(reverse('polls:detail',
args=(future_question.id,)))
self.assertEqual(response.status_code, 404)
def test_detail_view_with_a_past_question(self):
"""
The detail view of a question with a pub_date in the past should
display the question's text.
"""
past_question = create_question(question_text='Past Question.',
days=-5)
response = self.client.get(reverse('polls:detail',
args=(past_question.id,)))
self.assertContains(response, past_question.question_text,
status_code=200)
Tips
gte, lte seems to me, it is less, greater.
You do not need to have your app running when you doing the tests. Run the test like this
>python manage.py test polls
Creating test database for alias 'default'... .......... ---------------------------------------------------------------------- Ran 10 tests in 0.039s
Some Issues and Fixes
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.http import Http404
from polls.models import Question, Choice
# Create your views here.
def index(request):
latest_question_list = Question.objects.filter(
pub_date__lte = timezone.now()
).order_by('-pub_date')[:5]
#latest 5 records
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Question.objects.filter(
pub_date__lte = timezone.now()
).get(pk=question_id)
except Question.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'question': question})
References:
https://docs.djangoproject.com/en/1.7/intro/tutorial04/
https://docs.djangoproject.com/en/1.7/intro/tutorial05/
More Topic
https://docs.djangoproject.com/en/1.7/topics/
How to deploy
https://docs.djangoproject.com/en/1.7/howto/deployment/
Spawn-fcgi, wsgi, fastcgi, cgi
http://lihuipeng.blog.51cto.com/3064864/890573
- 浏览: 2551335 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
Stop Update Here
2020-04-28 09:00 315I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 475NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 367Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 368Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 336Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 430Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 435Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 373Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 454VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 384Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 477NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 422Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 246GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 450GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 326GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 313Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 317Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 292Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 311Serverless with NodeJS and Tenc ...
相关推荐
官方离线安装包,亲测可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,亲测可用。使用rpm -ivh [rpm完整包名] 进行安装
资源分类:Python库 所属语言:Python 资源全名:Django-3.2.11-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
官方离线安装包,亲测可用
`django-contact-form-1.5.tar.gz` 是一个用于Python后端开发的资源包,它专注于Django框架中的联系表单功能。Django是Python最流行的Web开发框架之一,以其高效、安全和可扩展性而闻名。`django-contact-form` 是...
Python在线考试系统后端-大学毕业设计-基于Django+Django -Rest-Framework 适合大学生计算机专业的毕业设计,课程设计。 Python在线考试系统后端-大学毕业设计-基于Django+Django -Rest-Framework 适合大学生...
资源分类:Python库 所属语言:Python 资源全名:django-contact-form-recaptcha-1.6.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
django-python3-ldap, python 3的Django LDAP用户身份验证后端 django-python3-ldapdjango-python3-ldap 为 python 2和 3提供了一个 Django LDAP用户身份验证后端。特性使用LDAP服务器验证用户身份。将LDAP用户与...
**Python库 django-mass-post-office-0.0.6** `django-mass-post-office` 是一个专门为Python的Django框架设计的邮件批量发送库。它允许开发者高效地处理大规模的邮件发送任务,对于构建需要频繁发送邮件的服务或者...
资源分类:Python库 所属语言:Python 资源全名:djangocms-cameraslider-0.1.2.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:django-wkhtmltopdf-3.2.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:django-form-builder-0.9.18.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
本着“挂一漏万、以点带面、以偏概全”的宗旨,以“在线学习”的应用为载体,深化对Django的理解,继续讲解一些新的技能。假设需要在网站中设计一个页面,这个页面用于向浏览者介绍网站,也就是所谓的“关于本站”。...
资源分类:Python库 所属语言:Python 资源全名:django-cascading-dropdown-widget-0.2.6.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:django-crispy-contact-form-0.1.11.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
支持python3.6Django2.0-goflow 工作流引擎 a
资源分类:Python库 所属语言:Python 使用前提:需要解压 资源全名:django_flags-4.2.1-py2.py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:django-pyodbc-azure-1.2.10.zip 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:django-mass-post-office-0.0.8.linux-x86_64.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059