PyCharmのヘルプにある「ステップ 4.最初のDjangoプロジェクトの作成と実行」でcssが反映されない問題がありました。
その内容と解決策を紹介します。
目次
NGケース(cssが反映されない)
手順の通りに以下のようなソースを記述します。
polls/url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
polls/index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
polls/static/polls/style.css
li a {
color: green;
}
以上で、127.0.0.1:8000/polls/ を表示させるとリストが緑色で表示されるという説明になっています。
しかし実際は反映されず、以下のように色の変更はありません。
OKケース(cssが反映される)
そこで、以下のようにソースを修正します。
- url.pyに名前空間を追記する。
app_name = ‘polls’ - index.htmlのdetailを名前空間を指定して記述する。
‘polls:detail’
polls/url.py
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
polls/index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
この状態で、127.0.0.1:8000/polls/ を再度表示させます。
すると以下のようにcssの内容が反映され、リストが緑色に変わります。
参考
名前空間(app_name = ‘polls’)を定義したことで、後続のtests.pyでもエラーが出るようになります。
そこで以下のように修正します。
response = self.client.get(reverse('polls:index')) # polls: という名前を指定する
polls/test.py
import datetime
from django.urls import reverse
from django.test import TestCase
from django.utils import timezone
from .models import Question
def create_question(question_text, days):
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
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'], [])

