Setup a Django Project with a MySQL database.

Posted on in Django MySQL Python

This tutorial requires Python 2.7.

First make sure virtualenv is installed:
$ pip install virtualenv

To set up a virtual environment for your project, use:
$ virtualenv myproject

To join the environment:
$ source myproject/bin/activate

Install Django:
$ pip install Django

Create a Django project.
$ django-admin startproject mysite

By default Django will make use of sqlite3. But for a production site, MySQL would be better.
I’m running XAMPP on Mac OS X, which includes MySQL already, so I will make use of this installation. When you don’t have MySQL on your machine, you can make a fresh install.

Download the MySQL Community Server from the official site. Select your platform and download the file. For a Mac OS X, you should have a .dmg file. After clicking on it to install MySQL, you will have to double click on the .pkg file to install it.
Next, we need to modify the $PATH so that the mysql command lines are available in your terminal. Edit the ~/.bash_profile file and add the following:
export PATH=$PATH:/usr/local/mysql/bin

Then restart your terminal, and start MySQL:
$ sudo /usr/local/mysql/support-files/mysql.server start
(In my case, I just had to start MySQL from the XAMPP quickstart app.)

Next, create a username with a password:
$ mysqladmin -u root password yourpassword

If you need to change the root password use:
$ mysqladmin -u root -p'oldpassword' password newpassword
Note: there is no space between the -p and the old password.

(Since I already have a working user account, and MySQL with PHPMyAdmin running, I could skip this last step)

Next, open mysql using the root account, and enter your password.
$ mysql -u root -p
Or if you rather use PhpMyAdmin, login to http://localhost/phpmyadmin
And go to the SQL tab.

Run the following query, with your database name, and username + password:

CREATE DATABASE mydatabase;
CREATE USER 'username'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'username'@'localhost';
FLUSH PRIVILEGES;

You can check the grants for a given user with:
show grants for 'username'@'localhost';

Once the database is correctly setup, you can install the Python MySQL adapter, from the command-line:
$ pip install mysqlclient

NOTE: The mysqlclient, will refer to a libmysqlclient.x.dylib file on your local machine. It's important that the folder which contains this file (it comes with your MySQL installation), has been added to the system variables / $PATH variables.

Open mysite/settings.py, edit the databases block:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'username',
        'PASSWORD': 'your_password',
        'HOST': '',
        'PORT': '',
    }
}

Also, make sure the timezone is correctly setup:
TIME_ZONE = 'CET'

Save the file, and run the following commands from the command-line, to use the database in your Python project:

$ python manage.py check
$ python manage.py migrate

Now you have to create a superuser for your project:
$ python manage.py createsuperuser

Let’s finish our application, and add the administration back-end.

Open mysite/urls.py and make sure the following lines are present:

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

You can start with running the python server, from the mysite folder:
$ python manage.py runserver

You can test and see if MySQL is correctly working, by logging into the Django admin panel. You could create a new user, this one should be available in the MySQL auth_user table.
From here, you can make changes to the database tables and properties, so be careful because they will interfere with the structure defined in your Django models.

Good luck!

Create dynamic Sencha models from your server-side

Posted on in Ext JS Sencha Sencha Touch

Every now and then I get this question in my Sencha training classes: "How can I dynamically create Sencha Models from my server-side?", or "How can I dynamically inject fields?" Normally you would define a Sencha Model like this:

Ext.define('App.model.MyModel', {
  extend: 'Ext.data.Model',
  
  fields: [{
     name: 'id',
     type: 'int'
  }, {
    name: 'firstname',
    type: 'string'
  }, {
    name: 'lastname',
    type: 'string'
  }]

});

The previous code is a Model class definition written in Ext JS. In Sencha Touch, it's almost the same, you would wrap the fields array in a config object. Defining Models this way, is perfect, but sometimes you would like to generate your Models from the server-side. For example, because you are using lots of fields, field names often change and you don't want to maintain the fields on two places (server-side vs. client-side). Mind you, also the data-type or field validations, needs to be in sync on both places, to not experience funny behavior.

So? Is it possible to create dynamic models? How does that work?

Let's say we have a PHP & MySQL server-side. I'm not gonna show you my PHP skills, since it has been a while. (..but if you are really curious, please leave a comment, then I can see if I can share some codes). But you will need to request the database schema. With MySQL I could write the following SQL statement: SHOW COLUMNS FROM mytable, where mytable is my database table name. This will return an Array with all my database fields.

The next step is to output JSON. I only care about the field names, and the field types. But... the MySQL data-types are different then the data-types in Ext JS / Sencha Touch, so I somehow need to map a varchar to a string etc. After that's done, my JSON output should look something like this:

{
  success: true,
  fields: [{
    name: "id",
    type: "int"
  },{
    name: "fname",
    type: "string"
  },{
    name: "lname",
    type: "string"
  }]
}

Now we are getting somewhere. These are the fields I dynamically want to inject in my Sencha Model. I can do this with an Ext.Ajax.request. Take a look:

Ext.define('App.store.MyStore', {
  extend: 'Ext.data.Store',
  
  constructor: function(){
      var me = this;
      me.callParent();

      Ext.Ajax.request({
        url: '../data/phpscript/?action=schema',
        success: function(response) {
          try{
            var resp = response.responseText;
            if(resp) {
              var data = Ext.JSON.decode(resp);

              var model = Ext.define("App.model.MyModel", {
                  extend: "Ext.data.Model",
                  fields: data.fields
              });

              me.model = model.$className;
            }
          }catch(e){
            console.error(e);
          }
        },
        failure: function(e){
          console.error(e);
        }
    });
  }
});

Here is what I did. I defined a Store, in the constructor I run an Ajax request, which fetches the fields array from my backend script, (in my case:) ../data/phpscript/?action=schema, which returns the JSON. In the success method, I create a model, and that's where I inject the fields.

Alright. Now hook up the Store to your app and test. You can run in your browser console the following line:

Ext.create('App.model.MyModel', { lname: "Boonstra" });

That should work, it will return the record, and you will see all the (empty) fields that this record contains.

Now that you get the idea, you will be pleased to know, that you can use similar tricks for injecting validations from the server-side or dynamically injecting grid columns... Woot woot.