12.08.2014

Django tips

Custom urls.py

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.(https://docs.python.org/2/reference/lexical_analysis.html#strings)

 https://docs.djangoproject.com/en/1.7/topics/http/urls/
 http://www.webforefront.com/django/regexpdjangourls.html

Static files for image, css

 https://docs.djangoproject.com/en/1.7/howto/static-files/


Directory of image files(MEDIA_ROOT)

 Your file will be uploaded in MEDIA_ROOT folder that defined in settings.py.
class Photo(models.Model):
    image_file = models.ImageField(upload_to='image')

 Image_file would go into the 'image' subdirectory of MEDIA_ROOT

  Example

  setting.py
....
MEDIA_URL = '/media/'  #HTTP
MEDIA_ROOT = os.path.join(BASE_DIR, 'static_files')


  urls.py

...
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

   model.spy
class Photo(models.Model):
    image_file = models.ImageField(upload_to='image')
   Your image file will be saved in ..../static_files/image/ . (setting.py, models.py)

   You can see your image file below address. (urls.py)
   http://ADDRESS/media/IMAGE_FILE


Get next model or previous model 


models.py

...
class Photo(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
view.py
...
def single_photo( request, photo_id) :
    photo = get_object_or_404(Photo, pk=photo_id)
    preveous_entry = photo.get_previous_by_created_at()
    next_entry = photo.get_next_by_created_at()

Get all objects or using specific filter

Photo.objects.all().order_by()[start_pos:end_pos]



 Apply to Templates.


settings.py
...
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'), ] #must be tuple
...
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Photo #photo.models
from django.template import Context, loader
def single_photo( request, photo_id) :
    photo = get_object_or_404(Photo, pk=photo_id)
    preveous_entry = photo.get_previous_by_created_at()
    next_entry = photo.get_next_by_created_at()   
    tpl = loader.get_template('photo.html')
    ctx = Context({
            'image2_url' : photo.filtered_image_file.url,
            'prev_entry': preveous_entry,
            'next_entry': next_entry,
            'prev_id': preveous_entry.id,
            'next_id': next_entry.id,
        })
    return HttpResponse(tpl.render(ctx))


photo.html


url.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^photo/(?P\d+)$', 'photo.views.single_photo', name = 'view_single_photo'),
)

Django nginx, gunicorn

django nginx, gunicorn