Remote access postgresql from external client (9.3)

1. Edit pg_hba.conf

vi /etc/postgresql/9.3/main/pg_hba.conf
host all all [CLIENT_IP]/24 trust

2. Edit postgresql.conf

vi /etc/postgresql/9.3/main/postgresql.conf
Find 'listen_addresses' and change to
listen_addresses = ‘*’

3. Restart postgresql

sudo service postgresql restart


First setting project with django.

Assume to finish basic setting by http://jeffgukang.blogspot.kr/2014/12/install-virtualenv-with.html

$ workon yourvirtualenv

2. Make Project
django-admin.py startproject yourproject
3. Setup setting.py file.

Make your database. (mysql, postgresql)

su postgres
$ CREATE DATABASE database_name; 

I edited settting.py for PostgreSQL
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '[_DBNAME_]
        'USER': '[_USERNAME_]',
        'PASSWORD': '[_DBPASSWORD_]',
        'HOST': 'localhost',
        'PORT': '',


Simple file upload with Model from templates in django 1.7.

 Django page describes how to upload files with form.

But if you want to upload file to model from your template, there is the simple way as follows.

1. Set url patch for POST method. 

urlpatterns = patterns('',
    url(r'^add/post/$', 'photo.views.add_post'),

2. Model that has file attributes. 

Your model has file attributes.
It can be any fileField including imageField.


class Photo(models.Model):
    id = models.AutoField(primary_key=True)
    image_file = models.ImageField() #auto uploded MEDIA foler fllowing settings.py
    filtered_image_file = models.ImageField()
    description = models.TextField(max_length=500, blank=True)

3. Make template form with file input.

Don't forget to write enctype="multipart/form-data" in your form tag.
{% csrf_token %} is for Cross site request forgery

    <form method="post" action="/add/post/" enctype="multipart/form-data">
        {% csrf_token %}
            <li><label for="description">Description</label></li>
            <li><input type="file" name="file" /></li>
            <li><textarea id="description" name="description"></textarea></li>
            <li><input type="submit" value="Finish" name="submit" /></li>

It looks like

4. File controller for POST method.

view.py will manage POST method from template.
File object will go into request.FILES if you write enctype="multipart/form-data" in your form tag.
And you are able to get the file object through request.FILES['_FILENAME_']

Process of file control is very similar with other languages as C, JAVA.
  1. Open temporary file stream with authorization.
  2. Write file in stream. 
  3. Close.

    When you treat model with file.
  4. Send file info to model that has file attributes. 
  5. Save model.


def add_post(request):
    message = 'done. '
    if request.method == 'POST' :
         photo = Photo()

        #file upload
        if 'file' in request.FILES :
            file = request.FILES['file']
            filename = file._name

            fp = open( '%s/%s' % (/filefolder/, filename), 'wb')
            for chunk in file.chunks() :
            photo.image_file = request.FILES['file']
            photo.filtered_image_file = request.FILES['file']
            message += 'file uploaded';

    try :
    except :
        return HttpResponse('Error!!!')

    return HttpResponse('I wrote %s' % message)

Run and check your files and admin site.

Cross-site request forgery (CSRF) issue when use POST form in django 1.7

Cross-site request forgery (CSRF)

I got a message when I tested to send POST form to server.

Forbidden (403)

CSRF verification failed. Request aborted.


Reason given for failure:

    CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function uses RequestContext for the template, instead of Context.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.

The reasons of CSRF verification fail are as follows.

By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.

The error page, however, is not very friendly, so you may want to provide your own view for handling this condition. To do this, simply set the CSRF_FAILURE_VIEW setting.


  1. Add the middelware in your setting.py. (I already have added it.)

        'django.middleware.csrf.CsrfViewMiddleware', #for csrf

    Alternatively, you can use the decorator csrf_protect() on particular views you want to protect (see below).
  2. Use the csrf_token tag in your any template that uses a POST form.
  3. Use RequestContext() instead of Context()
    def write_form(request) :
        page_title = 'Upload your photo'
        tpl = loader.get_template('write.html')
        # use RequestContext for csrf
        ctx = RequestContext(request, {
                'page_title': page_title,

        # ctx = Context({
        #     'page_title': page_title,
        # })
        return HttpResponse(tpl.render(ctx))

If you have a question how it works, read this.


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)


Static files for image, css


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


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


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

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

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)

Get next model or previous model 


class Photo(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
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


 Apply to Templates.

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'), ] #must be tuple
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))



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


Install virtualenv with virtualenvwrapper for python3.4 and django1.7 on Linux(ubuntu).

Virtual Environment(virtualenv) make easy to manage various environment for development.
It can create environment for each different version of python.

Install virtualenv.

$ sudo pip install virtualenv

Install virtualenvwrapper for easy control.

$ pip install virtualenvwrapper

Make virtualenv home directory.

$ mkdir ~/.virtualenvs

Setup for shell.

Write directory for work in ~/.bashrc
export WORKON_HOME=$HOME/.virtualenvs   
For execute virtualenvwrapper. (in ~/.bashrc)
source /usr/local/bin/virtualenvwrapper.sh
$ source ~/.bashrc

Make virtualenv for python3. (Assume python3.4 was installed.)

$ mkvirtualenv --python=/usr/bin/python3 [ENV_NAME]
It will make virtualenv in your WORKON_HOME directory.
$ workon
Check your python version.
$ python --version

Install django on your virtual env (1.7)

Go into your virtual env.
$ workon [ENV_NAME]

Install django.
$ pip install django

Basic command for management.

Check your virtualenv projects.
Go into virtualenv.
workon [ENV_NAME]
Deactivate from virtualenv.