Session in Django
ก่อนที่จะเริ่มทำ Hangman ยังมีเรื่องที่ต้องรู้อีกนิดนึง อย่างแรกก็คือ Session ทำมาตั้งนานยังไม่ได้พูดถึงซักนิด ใน Django นั้น session เป็นของเสริม ไม่ใช้ก็ไม่ต้องใส่ ช่วยได้นิดหน่อย จึงต้องพูดถึงนิดนึง เริ่มจาก middleware ต้องมี django.contrib.sessions.middleware.SessionMiddleware ใน MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', )
มี django.contrib.sessions ใน INSTALLED_APPS
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
และต้องสร้างตารางให้ด้วย ตอนนี้ยังไม่ได้ไปถึงฐานข้อมูล เราก็จะให้มันเก็บลงไฟล์ไปก่อน
SESSION_ENGINE = 'django.contrib.sessions.backends.file'แก้ settings.py แค่นี้พอแล้วสำหรับการใช้ session ต่อไปก็ลองใช้ เขียน view มาซักตัวใน heloworld/views.py
def count(request): i = request.session.get('count', 0) i = request.session['count'] = i+1 t = loader.get_template('helloworld/count.html') c = Context({ 'count': i, }) return HttpResponse(t.render(c))
คู่กับ templates/helloworld/count.html
{{ count }}แล้วก็ helloworld/urls.py
urlpatterns = patterns('', (r'^count$', 'django66.helloworld.views.count'), )
เสร็จแล้วก็ลองได้ http://localhost:8000/helloworld/count
Roti (alpha) thinks you may like these:







Post new comment