Python Console(三)Vesion Upgrade and Sample Form/Tests/Static/Customize
Python Console(3)Vesion Upgrade and Sample Form/Tests/Static/Customize
Python Console(3)Vesion Upgrade and Sample Form/Tests/Static/Customize
Write a simple form
this is really impressive about the form in the template
{% 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>
Action part to handle the form
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):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes +=1 selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Set up the namespace in urls.py
app_name = 'polls'
vote{{ choice.votes|pluralize }}
will display votes or vote. It is vote(s) depend on the choice.votes numeric
Use generic views: Less Code
…snip…
Automated tests
Command to run the test
>python manage.py test polls
Codes in polls/tests.py to test the DAO layer
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question
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.assertIs(future_question.was_published_recently(), False)
Test the View
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question.", pub_date=time)
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. """ time = timezone.now() + datetime.timedelta(days=30)
return Question.objects.create(question_text="Future question.", pub_date=time)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question.", pub_date=time)
time = timezone.now() + datetime.timedelta(days=30)
return Question.objects.create(question_text="Future question.", pub_date=time)
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question 1.", pub_date=time)
time = timezone.now() + datetime.timedelta(days=-5)
return Question.objects.create(question_text="Past question 2.", pub_date=time)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
It is really great to have these tests.
Way to load Static Resource
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
static/polls/style.css
li a {
color: green;
}
Load Image Resource
body {
background: white url("images/background.gif") no-repeat right bottom;
}
static/polls/images/background.gif
Customize the admin Form
This will adjust the properties order in the view
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice)
Use FieldSet
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
Add choice in the question Page
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
Another style
class ChoiceInline(admin.TabularInline):
Customize the Admin List
by default, it will display the str() of the object.
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date', 'was_published_recently')
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
list_filter = ['pub_date']
inlines = [ChoiceInline]
In object, we can make the view of was_published_recently shorter.
was_published_recently.short_description = 'Published recently?'
Add search Tag in the Console Page
search_fields = ['question_text’]
More documents
https://docs.djangoproject.com/en/1.11/topics/
References:
https://docs.djangoproject.com/en/1.11/intro/tutorial04/
https://docs.djangoproject.com/en/1.11/intro/tutorial05/
https://docs.djangoproject.com/en/1.11/intro/tutorial06/
https://docs.djangoproject.com/en/1.11/intro/tutorial07/
Python Console(3)Vesion Upgrade and Sample Form/Tests/Static/Customize
Write a simple form
this is really impressive about the form in the template
{% 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>
Action part to handle the form
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):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes +=1 selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Set up the namespace in urls.py
app_name = 'polls'
vote{{ choice.votes|pluralize }}
will display votes or vote. It is vote(s) depend on the choice.votes numeric
Use generic views: Less Code
…snip…
Automated tests
Command to run the test
>python manage.py test polls
Codes in polls/tests.py to test the DAO layer
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question
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.assertIs(future_question.was_published_recently(), False)
Test the View
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question.", pub_date=time)
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. """ time = timezone.now() + datetime.timedelta(days=30)
return Question.objects.create(question_text="Future question.", pub_date=time)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question.", pub_date=time)
time = timezone.now() + datetime.timedelta(days=30)
return Question.objects.create(question_text="Future question.", pub_date=time)
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. """ time = timezone.now() + datetime.timedelta(days=-30)
return Question.objects.create(question_text="Past question 1.", pub_date=time)
time = timezone.now() + datetime.timedelta(days=-5)
return Question.objects.create(question_text="Past question 2.", pub_date=time)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
It is really great to have these tests.
Way to load Static Resource
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
static/polls/style.css
li a {
color: green;
}
Load Image Resource
body {
background: white url("images/background.gif") no-repeat right bottom;
}
static/polls/images/background.gif
Customize the admin Form
This will adjust the properties order in the view
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice)
Use FieldSet
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
Add choice in the question Page
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
Another style
class ChoiceInline(admin.TabularInline):
Customize the Admin List
by default, it will display the str() of the object.
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date', 'was_published_recently')
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
list_filter = ['pub_date']
inlines = [ChoiceInline]
In object, we can make the view of was_published_recently shorter.
was_published_recently.short_description = 'Published recently?'
Add search Tag in the Console Page
search_fields = ['question_text’]
More documents
https://docs.djangoproject.com/en/1.11/topics/
References:
https://docs.djangoproject.com/en/1.11/intro/tutorial04/
https://docs.djangoproject.com/en/1.11/intro/tutorial05/
https://docs.djangoproject.com/en/1.11/intro/tutorial06/
https://docs.djangoproject.com/en/1.11/intro/tutorial07/