Archive

Archive for the ‘Framework’ Category

Create Django App and Data Model

April 23, 2017 1 comment

Creating Django App

To manage a project, django divide the project into several small django apps. Django app is a group of related functionality used to complete or maintain one aspect of a site.

The following command will create django app called myapp

$ python manage.py startapp myapp

To make django load the app, we need to add app name in django setting:

$ nano mysite/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # project app
    'myapp'
]

Creating Data Model

We often need to store our data into database. In django, we need to define our data model first, then make django to propagate data model creation/changes to database schema by using django commands. In this example, we will create data model inside of django app that we created before.

  1. Create data model
    $ nano myapp/models.py
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    
    class MyModel(models.Model):
        foo = models.IntegerField(default=0)
        bar = models.TextField(blank=True, null=True)
    
        class Meta:
            db_table = 'my_model_tbl'
  2. Make django migration
    $ python manage.py makemigrations myapp
  3. Apply changes to database schema
    $ python manage.py migrate myapp

     

Advertisements
Categories: Django, Framework

Install Django with Postgresql

April 22, 2017 Leave a comment

This post will guide you quickly step-by-step installing django and Postgresql on Linux Mint.

  1. Install Postgresql Server
    $ sudo apt-get install postgresql
  2. Switch account to postgres and create db user for django project (create non superuser that can create db)
    $ sudo -i -u postgres
    $ createuser djangouser -P --interactive
  3. Connect to postgresql server as djangouser and create db for django project
    $ psql -u djangouser -h localhost -d postgres -W
    $ create database django_project_db
  4. Create Django Environment and install postgres db adapter for python
    $ mkvirtualenv django-project
    $ pip install django psycopg2
  5. Create Django Project
    $ django-admin startproject mysite
  6. Change django project db settings
    $ cd mysite
    $ nano mysite/settings.py
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'django_project_db',
            'USER': 'djangouser',
            'PASSWORD': 'djangouser',
            'HOST': 'localhost',
            'POST': '5432'
        }
    }
  7. Initialize DB data for django project
    $ python manage.py migrate
  8. Test by running the server
    $ python manage.py runserver 0.0.0.0:8000

     

Categories: Django, Linux

Facebook Login with Code Igniter

January 7, 2015 1 comment

Requirement:

  • Code Igniter 2
  • Facebook SDK 3.2.3 (consist of facebook.php & base_facebook.php, put them in libraries folder)

Controllers Code

  • application/controllers/user_auth.php (Handle login process)
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class User_auth extends MY_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
        
        private function load_fb()
        {
            $fb_config = array(
                'appId'  => $this->config->item('apps_facebook_id'),
                'secret' => $this->config->item('apps_facebook_secret'),
            );
            
            $this->load->library('facebook',$fb_config);
        }
        
        public function login()
        {
            $this->load->helper('url');
            $this->load_fb();
            $user = $this->facebook->getUser();
    
            if($user)
            {
                try 
                {
                    $profile_data = $this->facebook->api('/v2.1/me?fields=id');
                    $this->session->set_userdata(
                      'blablabla',intval($profile_data['id'],10)
                    );
                } 
                catch (FacebookApiException $e) 
                {
                    $user = null;
                }            
            }
            else
            {
                $this->facebook->destroySession();
            }   
            redirect(site_url('welcome/index'));
        }
        
        public function logout()
        {
            
            $this->session->unset_userdata('blablabla');
            redirect(site_url('welcome/index'));    
        }
    }
    
    ?>
  • application/controllers/welcome.php (User access /welcome/index page)
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Welcome extends MY_Controller
    {    
        public function __construct()
        {
            parent::__construct();
        }
        private function load_fb()
        {
            $fb_config = array(
                'appId'  => $this->config->item('apps_facebook_id'),
                'secret' => $this->config->item('apps_facebook_secret'),
            );
            
            $this->load->library('facebook',$fb_config);        
        }
        
        public function index()
        {   
            $this->load->helper('url');
            $fb_id = intval($this->session->userdata('blablabla'),10);
            $page_data = array();
            if(!empty($fb_id) && ($fb_id>0) )
            {
                $page_data['facebook_data']['logged_in'] = true;
                $page_data['facebook_data']['logout_url'] = 
                               site_url('user_auth/logout.php');
            }
            else
            {
                $page_data['facebook_data']['logged_in'] = false;
                $this->load_fb();
                $page_data['facebook_data']['login_url'] = 
                  $this->facebook->getLoginUrl(array(
                    'display' => 'popup',
                    'redirect_uri' => site_url('user_auth/login.php'), 
                    'scope' => array("email,public_profile,user_friends")
                ));
                
            }
            
            $this->load->view('welcome_view', $page_data);
        }
        
    }
    
    ?>

View Code

  • application/views/welcome_view.php (Put login/logout button  here)
    <html>
    <head>
      <title>Hello</title>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>
        window.fbAsyncInit = function () {
          FB.init({
            appId: '<?php echo $facebook_data['apps_id'] ?>',
            version : 'v2.1',
            status: true,
            cookie: true,
            xfbml: true
          });          
        };
    
        (function (doc) {
          var js;
          var id = 'facebook-jssdk';
          var ref = doc.getElementsByTagName('script')[0];
          if (doc.getElementById(id)) {
            return;
          }
          js = doc.createElement('script');
          js.id = id;
          js.async = true;
          js.src = "//connect.facebook.com/en_US/sdk.js";
          ref.parentNode.insertBefore(js, ref);
        }(document));
        
        function Login() {
          FB.login(function (response) {
            if (response.authResponse) {
              location.replace(<?php echo site_url("user_auth/login.php");?>);
            } else {
              alert("Login attempt failed!");
            }
          }, { scope: 'email,public_profile,user_friends' });
        }
    </script>
    <div id="top_menu">
        <?php if(isset($facebook_data['logged_in']) && 
                 ($facebook_data['logged_in'] != false)  ) : ?>
            <div id="logout">
              <a href="<?php echo $facebook_data['logout_url'];?>" >Logout</a>
            </div>
        <?php else : ?>
            <div id="login">
              <a onclick="Login();" href="javascript:void(0);" >Login</a>
            </div>
        <?php endif; ?>
    </div>
    </body>
    </html>