Sugree

Main menu

  • About
    • Self
  • Project
    • Barcode Generator / Reader
    • GT200
    • GeoPin
    • Mitter
    • Red Mob
    • Thairath Breaking News
    • Twitter Android SDK
    • jibjib
    • microblog-purple
    • English
    • Thai

Session in Django

Submitted by sugree on Wed, 09/17/2008 - 12:08
  • Django
  • Python
  • Thai

ก่อนที่จะเริ่มทำ 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:
  • Simple template in Django
  • MVC in Django
  • Django - Hello, World!
  • Django 66 - Django Thailand
  • Loop in template
  • Login to post comments

Popular Tags

Android BarCamp BarCampBangkok Book Django Drupal Education Family Google Hardware Hardy Health Interview Intrepid Java jibjib Joke Life microblog-purple OpenOffice.org OpenSource Podcast Python Review SoC Social Network Trip Twitter Ubuntu Weekly Suki
more tags

Powered By

debian
apache
drupal
drupal.in.th
openfreehost
inox
feedburner

© 2007-2008 Sugree Phatanapherom. Creative Commons [Feed Content / Comment]
RoopleTheme