17
17

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のコンソールにデバッグのメッセージを出力する方法

Posted at

通常のDjangoの設定では,コンソールにデバッグメッセージが出力されないのでsetting.pyに設定を書かなくてはいけません.
print文でも出力はできますが,loggingで表示した方が健康的ですし,多くの情報を表示することができます.

setting.pyの最後の行に以下を追加します.
logging.basicConfigによってフォーマットを自由に設定できるようです.

setting.py
import logging

# For debugging 
if DEBUG:
    # will output to your console
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
    )
else:
    # will output to logging file
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
        filename = '/my_log_file.log',
        filemode = 'a'
    )

デバッグメッセージの出力は,logging.debug()で表示することができます.

import logging

def article_edit(request, pk):
    post = get_object_or_404(Article, pk=pk)
    if request.method =="POST"
        # コンソールにデバッグメッセージを出力する
        logging.debug('debug message')
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('article_detail', pk = post.pk)
    else:
        form = ArticleForm(instance=post)
    return render(request, 'blog/article_edit.html', {'form' : form})

loggingの詳細は以下を参考にしてください.
https://docs.djangoproject.com/en/1.11/topics/logging/

17
17
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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?