3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Django】django-debug-toolbarを利用する時のメモ

Last updated at Posted at 2017-01-20

Vagrantで構築したCentOS上にてDjangoを利用したWebアプリケーションを開発をした時、django-debug-toolbarを利用しようとしたらハマったのでメモ

#環境

  • CentOS 6.8
  • Django 1.10.5
  • Python 3.5.2
  • djang-debug-toolbar 1.6

#django-debug-toolbarのインストール

#pip install django-debug-toolbar

インストール結果

#pip list --format=columns

Package               Version
--------------------- -------
django-debug-toolbar  1.6    

今回は1.6がインストールされた

#REMOTE_ADDRの確認
確認方法はいろいろとあると思うけれど、自分は以下の方法で対応

example_app/view.py
from django.http import HttpResponse
from django.shortcuts import render
from app1.models import Ipaddress
	
	
def test(request):
    ip_addr = request.META['REMOTE_ADDR']
    return render(request,
        'test.html',
        {'ip_addr' : ip_addr}
        )
        
test.html
{{ ip_addr }}
example_app/urls.py

from django.conf.urls import url
from examle_app import views

urlpatterns = [
    url(r'^test/$', views.test, name='test'),

]
example_project/urls.py
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^example_app/', include('example_app.urls', namespace = 'example_app')), #ここを追記
]

この状態でrunserverし、http://IPアドレス:8000/example_app/test/ にアクセスすると、REMOTE_ADDRが表示されるはず

#setting.pyの編集
setting.pyの状態を確認し、不足している部分を追記する

setting.py
...

DEBUG = True

INTERNAL_IPS = ('127.0.0.1', 'ここにREMOTE_ADDRを書く',)

...


INSTALLED_APPS = [
    ...
    'debug_toolbar', 
    ...
]

...


MIDDLEWARE = [
    ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
	...
]

...

STATIC_URL = '/static/'

...

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TEMPLATE_CONTEXT': True,
}

#プロジェクト側のurls.pyを編集
プロジェクト側のurls.pyに以下を追記

example_project/urls.py
from django.conf import settings

...
...

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]

#ページを確認
WEBサーバを起動し、ページを確認すると、画面右側にdebugToolbarが表示されているはず

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?