Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, February 19, 2015

What is JSON ?

JSON stands for Javascript Object Notation.
Some descriptions are:

  • Format for sharing data
  • Derived from Javascript
  • Language independent (Originated with Js but availabe in many other language like PHP, C, Pearl, python)
  • An alternative to XML

Advantages:
  •  Leaner than XML
  • Easy to read
  •  Growing support in APIs
  • Natural format for Javascript
  • Implementation in many languages

Sunday, February 2, 2014

hide fields in django forms

Suppose we have the following model:

models.py:

from django.db import models

# Create your models here.
class Article(models.Model):
    name= models.CharField(max_length=200)
    country= models.TextField()
    bdate = models.DateTimeField('date published')
    age= models.IntegerField(default=1, null=True, blank=True)

forms.py:

from django import forms
from models import Article

class ArticleForm(forms.ModelForm):

    class Meta:
        model = Article

The above form will show all the four (04) fields.
To hide may be the age of the student, we'll modify the forms.py as follows:

forms.py:

from django import forms
from models import Article

class ArticleForm(forms.ModelForm):

    class Meta:
        model = Article
        fields = ('name', 'country', 'bdate')

 

Done !!

Django model : defautl, blank and null

from django.db import models

# Create your models here.
class Student(models.Model):
    age= models.IntegerField(default=1, null=True, blank=True)


No comment

Monday, January 13, 2014

Best tutorial for Django

I know this is apparently a hot topic that may raise a lot of discussion, however having wasted a substantial amount of my time trying and searching the best doc to get started with django framework I came to this conclusion. The Django Book is the most comprehensive place to get get started with    Django.       Being online it is  regularly updated compared to other books  you may have out there.
That said you are warned, don't go waste your precious time out there trying to find NOTHING.
You can easily use the scrapbook addon of firefox to download the entire website and read it offline.
You too if you have found something better please don't hesitate to share it  with us...

Monday, January 6, 2014

unexpected keyword argument 'maxlength' in Django

This problem arise because you are using the latest version of django. Just replace maxlength with max_length.  If you really want to keep using maxlength you must downgrade to django .96.
I hope it removes your road block, have a safe coding journey. See you next time...

python manage.py validate no module named image error

Are you victim of Django ImageField from your model declaration and keep getting "no module named image error" ? Ok, chances are that you have not installed the PIL or  python image library.

Just download and install the latest version and keep rocking. 

Sunday, January 5, 2014

ImproperlyConfigured: Requested setting TEMPLATE_DEBUG, but settings are not configured.

Maybe you want to test your first django template but keep getting this annoying error message. You certainly getting this error because you are misusing the shell. You are using python shell instead of a django managed shell. Saying this, what do i really mean. Suppose you want to test the following template:
>>> from django.template import Context, Template
>>> t = Template("Hello {{ name }}.")
>>> c = Context({"name": "World"})
>>> t.render(c)
Instead of running the above script from the python shell, go the command prompt ( if you are using winodws os)

cmd>django-admin.py startproject dummyProject
cmd> cd dummyProject
dummyProject> python manage.py shell
>>> 
>>> from django.template import Context, Template
>>> t = Template("Hello {{ name }}.")
>>> c = Context({"name": "World !"})
>>> t.render(c)
Hello World !

Congratulation , you just run your first django template.

Saturday, January 4, 2014

Sqlite3 installation on windows

So you want to install sqlite3 and wonder how to do so because there is no single executable file to click on and follow up ?
No problem just go to sqlite3 download page  and under the Precompiled Binaries for Windows part, download the following three file and unzip them.
-sqlite-shell-win32-x86-xxx.zip
-sqlite-dll-win32-x86-xxx.zip
-sqlite-analyzer-win32-x86-xxx.zip


Then after unzipping them put, paste the unzipped files in C:\windows\System32

That is all, now from your command prompt terminal (CMD) type: sqllite3 and your are in.
sqlite>.help

Installing Django on Windows 7 in less than 5 minutes

Out there, there are many tutorials but I think this one may just make the differece.
I assume that you have downloaded a python 2.7.x  and copy of Django 1.6.x .I also suppose that you are familiar with cmd commands like cd, dir , cd.., etc

Step ONE: Install Python
Click on the Python just downloaded to launch the installation. Just follow next and all the defaults.
It should be installed in C:\python27.

Step TWO: Make Python available in the terminal (cmd):
To do this you have to register it as system variables.
Right-Click Properties --> Advanced system settings -->Environment Variables -->System variable -->path -->Edit: and paste the following.
;C:\Python27;C:\Python27\Scripts;C:\Python27\DLLs\;C:\Python27\Lib\;

Step THREE: install Django
Unzip the downloaded compressed folder under the C: drive.
Go to the Command prompt CMD and navigate inside the C:\Django 1.6.x folder.
> cd C:\Django 1.6.x
 C:\Django 1.6.x> python.exe setup.py install 
Please wait till all is done. 

Step FOUR: Create a Django Project Go to a location where you want to create your project. Our project name is ido.

cmd ..> django-admin.py startproject ido
 ..ido> python.exe manage.py runserver

Step FIVE: Launch it.
 Just open your browser and type:
 http://127.0.0.1:8000

By now you should have your project available. Feel free to amend.

Friday, January 3, 2014

OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

I came across this disgusting  error message while try to connect to mysql in python 2.7.
In fact I wrote something like :
import MySQLdb
db = MySQLdb.connect(host="localhost", user="py", passwd="py", db="test")

You can get rid of the above mentioned error by just replacing the host: localhost by 120.0.0.1

import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", user="py", passwd="py", db="test")
...

Thursday, January 2, 2014

Collection data types in Python: Sequence vs Sets vs Mappings

No matter what some folks will argue or say, understanding key differences between python collection  data types is essential to pave your way from much headaches. I got this important explanation from this book . In fact in python or even other similar programming languages we have three types of Collection data types : Sequences, sets and mappings.

Sequences:  A sequence type is one that supports the membership operator (in), the sizefunction (len()), slices ([]), and is iterable. Python provides five built-in sequence types: bytearray, bytes, list, str, and tuple:
  •  Tuples: A tuple is an ordered sequence of zero or more object references. It supports the same slicing and striding syntax as  strings.Like strings, tuples are immutable, so we cannot replace or delete any of their items. If we want to be able to modify an ordered sequence, we simply use a list instead of a tuple; or if we already have a tuple but want to modify it, we can convert it to a list using the list() conversion function and then apply the changes to the resultant list.   e.g: myTyple= 'soulemane', 'cse', 2014, -1, 'y'
  • Lists: A list is an ordered sequence of zero or more object references. Lists support the same slicing and striding syntax as strings and tuples. This makes it easy to extract items from a list. Unlike strings and tuples, lists are mutable, so we can replace and delete any of their items. It is also possible to insert, replace,and delete slices of lists.
e.g:  myList= ['soulemane', 'cse', 2014, -1, 'y']


Sets: A set type is a collection data type that supports the membership operator (in), the size function (len()), and is iterable.Python provides two built-in set types: the mutable set type and the immutable frozenset. When iterated, set types provide their items in an arbitrary order.
      All the built-in immutable data types, such as float, frozenset, int, str, and tuple, are hashable and
can be added to sets. The built-in mutable data types, such as dict, list, and set, are not hashable since
their hash value changes depending on the items they contain, so they cannot be added to sets.
  •  Sets: A set is an unordered collection of zero or more object references that refer tohashable objects. Sets are mutable, so we can easily add or remove items, but since they are unordered they have no notion of index position and so cannotbe sliced or strided.
e.g:  myList= {'soulemane', ('cse', 2014), -1, 'y'}
  • Frozen Sets: A frozen set is a set that, once created, cannot be changed. We can of course rebind the variable that refers to a frozen set to refer to something else, though. Frozen sets can only be created using the frozenset data type called as a function.  Since frozen sets are immutable, they support only those methods and operators that produce a result without affecting the frozen set or sets to which they are applied.
Mappings:  A mapping type is one that supports the membership operator (in) and the size function (len()), and is iterable. Mappings are collections of key–value items and provide methods for accessing items and their keys and values. When iterated, unordered mapping types provide their items in an arbitrary order.  
         Only hashable objects may be used as dictionary keys, so immutable data types such as float, frozenset, int, str, and tuple can be used as dictionary keys, but mutable types such as dict, list, and set cannot. On the other hand, each key’s associated value can be an object reference referring to an object of any type, including numbers, strings, lists, sets, dictionaries, functions, and so on.
  • Dictionaries: A dict is an unordered collection of zero or more key–value pairs whose keys are object references that refer to hashable objects,and whose values are object references referring to objects of any type. Dictionaries are mutable, so we can easily add or remove items, but since they are unordered they have no notion of index position and so cannot be sliced or strided.
e.g: myDict = dict({"Nb": 2014, "soulemane": "moumie", "salary": 10})
                  or
    myDict = {"Nb": 2014, "soulemane": "moumie", "salary": 10}

One important remarks is to notice maps or dictionary are defined with braces {} with each key-value pair element separated with a colon ,  sets are defined with braces {}, lists are defined with brackets [] ,  and tuples are directly and openly defined.