はじめに
前回と記事からの変更点
- データベースを作成する際に文字コードを指定して作成する。日本語を文字化けさせないために。
create database <データベース名>;
alter database <データベース名> default character set utf8mb4;
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
サンプルコード
forms.py
from django import forms
from view.models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ('contact_name', 'contact_mailaddress','contact_subject','contact_message','contact_status','contact_attachment_file')
templates/form.html
<h1>Create New Contact2</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">投稿する</button>
</form>
from django.shortcuts import render
from django.http import HttpResponse
from view.forms import ContactForm
from django.shortcuts import redirect
import logging
logging.basicConfig(filename='/srv/backend/view/logs/example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
# Create your views here.
def contact(request):
logging.debug('Hello World!')
if request.method == 'POST':
form = ContactForm(request.POST)
logging.debug(form)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('index')
else:
form = ContactForm()
return render(request, 'form.html', {'form': form})
def index(request):
return HttpResponse("index Page")
ログ出力処理
- 下記の記述をすることでdjango上でログ出力することが可能である。
import logging
logging.basicConfig(filename='/path/logs/example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
画面