You are hereStatic files in Django

Static files in Django


By sugree - Posted on 20 September 2008

ในตอนแรกของการสร้าง app สำหรับอัพโหลด มีขั้นตอนสำหรับการใช้ไฟล์ภายนอกไว้หน่อยนึง นี่เป็นหนึ่งในสิ่งที่จำเป็นสำหรับการทำ Hangman วันนี้ก็มาขยายความกันนิดนึง

ใน Django มีวิธีรับมือกับไฟล์ภายนอกที่อยู่นิ่งๆ ไม่เปลี่ยนแปลงอยู่ในขั้นเกือบเทพ เหมาะกับ CDN มาก ใช้ก็ง่าย แค่ระบุ url ใน settings.py

MEDIA_URL = '/static_media/'

เวลาใช้จริงอาจจะเปลี่ยนเป็น url เต็มๆ อย่าง http://static.domain.com/ ได้ไม่ยาก

<!--break-->

ใน urls.py ก็เพิ่มนิดนึง เพื่อใช้สำหรับการพัฒนาในเครื่องตัวเอง

from django66 import settings
 
if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
    (r'^static_media/(?P<path>.*)$', 
        'serve', {
        'document_root': '/home/sugree/work/git/django66/django66/static_media'
        'show_indexes': True }),)

แล้วส่วนใน templates/helloworld/index.html ก็ใช้ {{ MEDIA_URL }} ได้ตามสะดวก

<html>
<head>
 <link rel="stylesheet" href="{{ MEDIA_URL }}style.css" ype="text/css" media="screen">
</head>
<body>
Hello, World!
</body>
</html>

และ static_media/style.css สร้างไว้สำหรับทดสอบ

body {
  font-size: 10em;
}

แต่ยังไม่ครบ ต้องเปลี่ยน helloworld/views.py นิดนึง

--- a/django66/helloworld/views.py
+++ b/django66/helloworld/views.py
@@ -1,10 +1,11 @@
-from django.template import Context, loader
+from django.template import Context, RequestContext, loader
+from django.shortcuts import render_to_response
 from django.http import HttpResponse
 
 def index(request):
-    t = loader.get_template('helloworld/index.html')
-    c = Context()
-    return HttpResponse(t.render(c))
+    return render_to_response('helloworld/index.html',
+                              {},
+                              context_instance=RequestContext(request))
 
 def entity(request, name):
     t = loader.get_template('helloworld/entity.html')

ออกมาแบบสั้นๆ ได้เป็น

from django.template import Context, RequestContext, loader
from django.shortcuts import render_to_response
 
def index(request):
    return render_to_response('helloworld/index.html',
                              {},
                              context_instance=RequestContext(request))

ขอแนะนำ shortcut ตัวใหม่ที่ช่วยลดความยาวได้นิดหน่อย นั่นคือ render_to_response() พระเอกของงานนี้คือ RequestContext() ที่จะส่งข้อมูลจาก context processors ให้ใช้ใน template ปกติจะมีค่าแบบนี้

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media"
)