Custom Search
Showing posts with label Django. Show all posts
Showing posts with label Django. Show all posts

Wednesday, June 11, 2014

Python Django Extending the existing User model with custom fields

1)
django-admin startproject mypro
django-admin startapp app1

2)
#vim mypro/app1/models.py

from django.contrib.auth.models import User
from django.db import models

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)



3)
#vim mypro/mypro/settings.py
* add 'app1' in INSTALLED_APPS

4)
#cd mypro
#python manage.py syncdb

5)
#cd mypro
#python manage.py shell


>>> from django.contrib.auth.models import User
>>> u = User.objects.all()[0]
>>> u.employee
>>> u.empoyee.department

----------

>>> e = Employee()
>>> e.user = u
>>> e.department = "dddddd"
>>> e.save()
>>> u.employee

>>>
>>>
>>> u.employee.department
'dddddd'

----------

Friday, February 14, 2014

Django local_settings.py how to add apps in INSTALLED_APPS

Django local_settings.py how to extend INSTALLED_APPS

1)
Add following lines in local_settings.py

ADDITIONAL_APPS = ('captcha', 'cities_light')try:
    from settings import INSTALLED_APPS
    INSTALLED_APPS = ADDITIONAL_APPS + INSTALLED_APPS
except:
    pass

Saturday, January 18, 2014

Django Working of CsrfViewMiddleware

1)
Usage
Option1)
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def your_view(request):
   ##blabla

Option2)
Include the class "django.middleware.csrf.CsrfViewMiddleware" in
settings.MIDDLEWARE_CLASSES

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

2)
site-packages/Django-1.5-py2.7.egg/django/views/decorators/csrf.py

csrf_protect = decorator_from_middleware(CsrfViewMiddleware)

3)
site-packages/Django-1.5-py2.7.egg/django/middleware/csrf.py


class CsrfViewMiddleware(object):
    """
    Middleware that requires a present and correct csrfmiddlewaretoken
    for POST requests that have a CSRF cookie, and sets an outgoing
    CSRF cookie.

    This middleware should be used in conjunction with the csrf_token template
    tag.
    """
    # The _accept and _reject methods currently only exist for the sake of the
    # requires_csrf_token decorator.
    def _accept(self, request):
        # Avoid checking the request twice by adding a custom attribute to
        # request.  This will be relevant when both decorator and middleware
        # are used.
        request.csrf_processing_done = True
        return None

    def _reject(self, request, reason):
        return _get_failure_view()(request, reason=reason)

    def process_view(self, request, callback, callback_args, callback_kwargs):

        if getattr(request, 'csrf_processing_done', False):
            return None

        try:
            csrf_token = _sanitize_token(
                request.COOKIES[settings.CSRF_COOKIE_NAME])
            # Use same token next time
            request.META['CSRF_COOKIE'] = csrf_token
        except KeyError:
            csrf_token = None
            # Generate token and store it in the request, so it's
            # available to the view.
            request.META["CSRF_COOKIE"] = _get_new_csrf_key()

        # Wait until request.META["CSRF_COOKIE"] has been manipulated before
        # bailing out, so that get_token still works
        if getattr(callback, 'csrf_exempt', False):
            return None

        # Assume that anything not defined as 'safe' by RFC2616 needs protection
        if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
            if getattr(request, '_dont_enforce_csrf_checks', False):
                # Mechanism to turn off CSRF checks for test suite.
                # It comes after the creation of CSRF cookies, so that
                # everything else continues to work exactly the same
                # (e.g. cookies are sent, etc.), but before any
                # branches that call reject().
                return self._accept(request)

            if request.is_secure():
                # Suppose user visits http://example.com/
                # An active network attacker (man-in-the-middle, MITM) sends a
                # POST form that targets https://example.com/detonate-bomb/ and
                # submits it via JavaScript.
                #
                # The attacker will need to provide a CSRF cookie and token, but
                # that's no problem for a MITM and the session-independent
                # nonce we're using. So the MITM can circumvent the CSRF
                # protection. This is true for any HTTP connection, but anyone
                # using HTTPS expects better! For this reason, for
                # https://example.com/ we need additional protection that treats
                # http://example.com/ as completely untrusted. Under HTTPS,
                # Barth et al. found that the Referer header is missing for
                # same-domain requests in only about 0.2% of cases or less, so
                # we can use strict Referer checking.
                referer = request.META.get('HTTP_REFERER')
                if referer is None:
                    logger.warning('Forbidden (%s): %s',
                                   REASON_NO_REFERER, request.path,
                        extra={
                            'status_code': 403,
                            'request': request,
                        }
                    )
                    return self._reject(request, REASON_NO_REFERER)

                # Note that request.get_host() includes the port.
                good_referer = 'https://%s/' % request.get_host()
                if not same_origin(referer, good_referer):
                    reason = REASON_BAD_REFERER % (referer, good_referer)
                    logger.warning('Forbidden (%s): %s', reason, request.path,
                        extra={
                            'status_code': 403,
                            'request': request,
                        }
                    )
                    return self._reject(request, reason)

            if csrf_token is None:
                # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
                # and in this way we can avoid all CSRF attacks, including login
                # CSRF.
                logger.warning('Forbidden (%s): %s',
                               REASON_NO_CSRF_COOKIE, request.path,
                    extra={
                        'status_code': 403,
                        'request': request,
                    }
                )
                return self._reject(request, REASON_NO_CSRF_COOKIE)

            # Check non-cookie token for match.
            request_csrf_token = ""
            if request.method == "POST":
                request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
                print "======csrff=======1===csrfmiddlewaretoken==" ,request_csrf_token
            if request_csrf_token == "":
                # Fall back to X-CSRFToken, to make things easier for AJAX,
                # and possible for PUT/DELETE.
                request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
                print "======csrff=======2===HTTP_X_CSRFTOKEN==" ,request_csrf_token

            print "======csrff=======3==request_csrf_token ===" ,request_csrf_token
            print "======csrff=======4==csrf_token===" ,csrf_token    
            if not constant_time_compare(request_csrf_token, csrf_token):
                print "======csrff=======5===errorrr=="
                logger.warning('Forbidden (%s): %s',
                               REASON_BAD_TOKEN, request.path,
                    extra={
                        'status_code': 403,
                        'request': request,
                    }
                )
                return self._reject(request, REASON_BAD_TOKEN)

        return self._accept(request)

    def process_response(self, request, response):
        if getattr(response, 'csrf_processing_done', False):
            return response

        # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was
        # never called, probaby because a request middleware returned a response
        # (for example, contrib.auth redirecting to a login page).
        if request.META.get("CSRF_COOKIE") is None:
            return response

        if not request.META.get("CSRF_COOKIE_USED", False):
            return response

        # Set the CSRF cookie even if it's already set, so we renew
        # the expiry timer.
        response.set_cookie(settings.CSRF_COOKIE_NAME,
                            request.META["CSRF_COOKIE"],
                            max_age = 60 * 60 * 24 * 7 * 52,
                            domain=settings.CSRF_COOKIE_DOMAIN,
                            path=settings.CSRF_COOKIE_PATH,
                            secure=settings.CSRF_COOKIE_SECURE
                            )
        # Content varies with the CSRF cookie, so set the Vary header.
        patch_vary_headers(response, ('Cookie',))
        response.csrf_processing_done = True
        return response


4)
site-packages/Django-1.5-py2.7.egg/django/utils/decorators.py


def decorator_from_middleware(middleware_class):
    """
    Given a middleware class (not an instance), returns a view decorator. This
    lets you use middleware functionality on a per-view basis. The middleware
    is created with no params passed.
    """
    return make_middleware_decorator(middleware_class)()

def make_middleware_decorator(middleware_class):
    def _make_decorator(*m_args, **m_kwargs):
        middleware = middleware_class(*m_args, **m_kwargs)
        def _decorator(view_func):
            @wraps(view_func, assigned=available_attrs(view_func))
            def _wrapped_view(request, *args, **kwargs):
                if hasattr(middleware, 'process_request'):
                    result = middleware.process_request(request)
                    if result is not None:
                        return result
                if hasattr(middleware, 'process_view'):
                    result = middleware.process_view(request, view_func, args, kwargs)

                    if result is not None:
                        return result
                try:
                    response = view_func(request, *args, **kwargs)
                except Exception as e:
                    if hasattr(middleware, 'process_exception'):
                        result = middleware.process_exception(request, e)
                        if result is not None:
                            return result
                    raise
                if hasattr(response, 'render') and callable(response.render):
                    if hasattr(middleware, 'process_template_response'):
                        response = middleware.process_template_response(request, response)
                    # Defer running of process_response until after the template
                    # has been rendered:
                    if hasattr(middleware, 'process_response'):
                        callback = lambda response: middleware.process_response(request, response)
                        response.add_post_render_callback(callback)
                else:
                    if hasattr(middleware, 'process_response'):
                        return middleware.process_response(request, response)
                return response
            return _wrapped_view
        return _decorator
    return _make_decorator


 

Tuesday, December 17, 2013

How to install django-cities-light and populate country region state and city dropdown

1)
pip install django-cities-light
pip install south

2)
Add "cities_light" to your INSTALLED_APPS.

3)
./manage.py syncdb



4)
Help
./manage.py help cities_light

5)
Populate tables
./manage.py cities_light

6)
#python manage.py shell
>>> import cities_light as cl
>>> cl.models.Country.objects.filter(name='india').all()
>>> cl.models.Region.objects.filter(name='kerala').all()
>>> cl.models.City.objects.filter(name='bangalore').all()

How to install django-cities and populate country region state and city dropdown

How to install django-cities and populate country region state and city drop-down

1)
a)
#easy_install django-cities
Note: easy_install did not work for me. I got following errror when tried to run "./manage.py cities --import=all"
AttributeError: type object '' has no attribute 'plugins'

b)
Works
---------

activate virtualenv
#git clone https://github.com/coderholic/django-cities.git
#cd django-cities
#python setup.py install




2)
Add 'cities' to INSTALLED_APPS in your projects settings.py file

3)
Change db backend

Goto settings.py and add/replace following line in DATABASES dictionary.
*'ENGINE': 'django.contrib.gis.db.backends.mysql'

4)
Create tables for the cities app
#python manage.py syncdb

5)
Optional

Add following file in settings.py
GEOS_LIBRARY_PATH = '/home/saju/horizon_test/geos-3.3.8/capi/.libs/libgeos_c.so'

6)
a)

#Download all data files to .venv/lib/python2.7/site-packages/django_cities-0.2-py2.7.egg/cities/data
#Then insert data to all tables
#./manage.py cities --import=all

b)
#Download only country file to .venv/lib/python2.7/site-packages/django_cities-0.2-py2.7.egg/cities/data
#Then insert data to country table
#./manage.py cities --import=country

c)
#./manage.py cities --help

d)
Debug: Clear downloaded files from following path and run "./manage.py cities --import=all" again.
#cd .venv/lib/python2.7/site-packages/django_cities-0.2-py2.7.egg/cities/data

7)
Test
#python manage.py shell
>>> import cities
>>> cities.models.Country.objects.all()[1]




Thursday, December 12, 2013

[Solved] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

1)
#sudo apt-get install python-mysqldb



2)
#easy_install MySQL-python

Friday, November 22, 2013

Python Django How to send email from python console

0)
First setup and configure email server (exim)

1)
Activate virtualenv

2)
Got you django project folder and run following command
#export DJANGO_SETTINGS_MODULE=myproject.settings



3)
Open python terminal and run following command
#python
import myproject.settings as setting


setting.EMAIL_HOST
setting.EMAIL_PORT
 

from django.core.mail import send_mail
 

send_mail('Subject here2', 'Here is the message1.', 'from@mymailserver.com', ['sajuptpm@gmail.com'], fail_silently=False)

Wednesday, November 6, 2013

Python Django Configure Exim Mail Server

1)Install Exim
#apt-get update
#apt-get upgrade
#apt-get install exim4-daemon-light mailutils



2)Configure Exim
#dpkg-reconfigure exim4-config

3)
Settings.py Changes
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

Sunday, October 20, 2013

How to access local django webserver from outside world

How to access local django webserver (python manage.py runserver) from outside world

1)
Start local webserver
#python mange.py runserver
Django version 1.5.1, using settings 'myapp.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

2)
In remote machine
http://ip-of-django-web-server:8000/

Friday, July 5, 2013

How to create my first migration script using south

How to created my first migration script using south

1)
Create Migration script for create tables for models
#python manage.py schemamigration myapp --initial

2)
Execute Migration Script
#python manage.py migrate myapp

3)
Check status
#python manage.py migrate --list

4)
Create a new Migration script "000x_add_content_type.py" for add entry to contenttype for new model
#python manage.py datamigration app_settings add_content_type --freeze=contenttypes --freeze=auth

5)
Edit the Migration script "000x_add_content_type.py" and override forward() method.
I added following line method forward()
ct, created = orm['contenttypes.ContentType'].objects.get_or_create(model='ielabexcludeyear', app_label='app_settings')

6)
Execute Migration Script
#python manage.py migrate myapp

7)
Add Permissions for new app and models
The command "add_group_permissions" is not the part of "south" tool
The command "add_group_permissions" is created using django' custom-management-commands feature.
https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
#python manage.py add_group_permissions

8)
http://fosshelp.blogspot.in/2013/07/how-to-use-django-south.html

Thursday, July 4, 2013

How to use django south

Install south
==========

http://south.readthedocs.org/en/latest/installation.html#using-easy-install

1)
Install south
---------------
#easy_install South

2)
Setting
----------
a) Add "south" to "settings.INSTALLED_APPS" and comment out all other apps
b) Then run "python manage.py syncdb"
c) Then uncomment all apps in the "settings.INSTALLED_APPS"
d) Then run "python manage.py runserver 8009" for testing

3)
Checking
----------
* Run "python manage.py --help" and you can see following commands provided by the "south" app.
[south]
    convert_to_south
    datamigration
    graphmigrations
    migrate
    migrationcheck
    schemamigration
    startmigration
    syncdb
    test
    testserver

4)
Note
---------------
http://south.readthedocs.org/en/latest/migrationstructure.html
When South loads migrations, it loads all the python files inside your app’s migrations/ directory in ASCII sort order (e.g. 1 is before 10 is before 2), and expects to find a class called Migration inside each one, with at least a forwards() and backwards() method.
When South wants to apply a migration, it simply calls the forwards() method, and similarly when it wants to roll back a migration it calls backwards()

Schema Migrations
===============

http://south.readthedocs.org/en/latest/tutorial/part1.html

1)
First step: Create a migrations directory inside our app.
---------------
* Run the command
#python manage.py schemamigration myapp --initial

*This command will create a migrations directory for us, and made a new migration inside it.

2)
How to apply/run our new migration script created by the command "python manage.py schemamigration myapp --initial"
How to create the tables
-----------------------------------
* Run the commmand
#python manage.py migrate myapp

* This command will create new tables for our models in the app "myapp"
* So we create a table witout using the command "python manage.py syncdb" <====

3)
How to update the tables
-------------------------
a) First change the moel definition (Eg: add a new column)
b) Create a new migration script using the option "--auto"
#python manage.py schemamigration myapp ----auto
c) Apply/Run the migration script created by the previous command
#python manage.py migrate myapp

4)
How to check the applied and not applied migration scripts
------------------------------------------------------------
#python manage.py migrate --list
* The output has an asterisk (*) next to a migration name if it has been applied, and an empty space ( ) if not

Data migrations
===============

* http://south.readthedocs.org/en/latest/tutorial/part3.html
* Data migrations are used to change the data stored in your database to match a new schema, or feature.

1)
Create an empty data migration script file
------------------------------------------
# python manage.py datamigration myapp my_script_file

2)
Open the data migration script file
-----------------------------------
#vim my_script_file.py
* In that file we can see models definitions, the forwards() and backwards() functions.
* Override the method "forwards()"

3)
Apply/Run the migration script
-------------------------------
#python manage.py migrate myapp

django how to fix Exception Value: 'int' object has no attribute '__getitem__'

django how to fix Exception Value: 'int' object has no attribute '__getitem__'

Solution
======
your model's __unicode__ method should return a unicode string

Django How to make entries into ContentType for new app

Django How to make entries into ContentType for new app
 

How to fix following errors
---------------------------

a) 
DoesNotExist: ContentType matching query does not exist. Lookup parameters were {'model': 'years', 'app_label': 'setting'}

b)

DoesNotExist: Permission matching query does not exist. Lookup parameters were {'codename': 'add_years', 'content_type': }

Solution
======

1)
Goto "settings.py" and keep only following lines in "INSTALLED_APPS".
INSTALLED_APPS = ['django.contrib.auth',
'django.contrib.contenttypes',
'iekb.mynewapp']

2)
Run syncdb
#python manage.py syncdb

Thursday, June 20, 2013

Django How to create json fixture from database table

1) Help
#python manage.py dumpdata --help

2) Create json fixture from table Template
#python manage.py dumpdata dbtemplates.Template  > ~/Desktop/template.json

Tuesday, October 25, 2011

howto django uploading files to dynamic path

def get_upload_path(instance, filename):
    """
        Get upload path
        eg: upload/1/2011/10/16/09/00/12/oauth_application.png
    """
    today = datetime.utcnow()
    date_time_str = today.strftime("%Y/%m/%d/%H/%M/%S")
    path = "%s/%s/%s/%s" %(storage, instance.user.id, date_time_str, filename)
#    print "---------", path
    return path


class MultiuploaderImage(models.Model):
    """Model for storing uploaded photos"""
    filename = models.CharField(max_length=60, blank=True, null=True)
    image = models.FileField(upload_to=get_upload_path)
    key_data = models.CharField(max_length=90, unique=True, blank=True, null=True)
    upload_date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)

Tuesday, February 15, 2011

Python django Passing a List or Dictionary as Arguments

Python django Passing a List or Dictionary as Arguments

================
>>> a={"s":1,"t":2}

>>> def k(a):
... print a
... a['u']=3
... print a
...
>>> a
{'s': 1, 't': 2}
>>>
>>>
>>> k(a)
{'s': 1, 't': 2}
{'s': 1, 'u': 3, 't': 2}
>>>
>>>
>>> a
{'s': 1, 'u': 3, 't': 2}
>>>


list
================
>>> a=[2,4]
>>>
>>>
>>> def k(a):
... print a
... a.append(6)
... print a
...
>>>
>>> a
[2, 4]
>>>
>>> k(a)
[2, 4]
[2, 4, 6]
>>>
>>> a
[2, 4, 6]
>>>



================

>>> a = ['2','4','6','8','10']
>>>
>>>
>>> "/".join(a)
'2/4/6/8/10'
>>>

================


More.....

Sunday, February 13, 2011

python boolean Operations and or not

python boolean Operations and or not

============ or =================

>>>
>>> a = 0
>>> b = 10
>>> c = a or b
>>> c
10

>>> ----------------------

>>> a = 5
>>> b = 10
>>> c = a or b
>>> c
5

>>> ---------------------

>>> a = None
>>> b = 10
>>> c = a or b
>>> c
10

>>> ---------------------

>>> a = ""
>>> b = 10
>>> c = a or b
>>> c
10


************************** Equal To

>>> a = None
>>> b = 10
>>> if not a:
... c = b
... else:
... c = a
...
>>>
>>> c
10

>>> ---------------------

>>> a = 5
>>> b = 10
>>> if not a:
... c = b
... else:
... c = a
...
>>>
>>> c
5




=============== and =================

>>>
>>> a = 5
>>> b = 10
>>> c = a and b
>>> c
10

>>> ------------------------

>>> a = 0
>>> b = 10
>>> c = a and b
>>> c
0

>>> ------------------------

>>> a = None
>>> b = 10
>>> c = a and b
>>> c

>>> ------------------------

>>> a = ""
>>> b = 10
>>> c = a and b
>>> c
''
>>>


==================================

More.....

Wednesday, January 26, 2011

python django working of object copy technique

python django working of object copy technique

class MyClass:

def __init__(self, name):
self.amount = 100
self.name = name

def test(self):
print "test"


m1 = MyClass('SAJU')

print "\n-------m1---------", m1
print "\n--------dir(m1)----------", dir(m1)
print "\n--------vars(m1)----------", vars(m1)
print "\n---------m1.__dict__-----------------", m1.__dict__
print "\n----------m1.__class__.__name__----------------", m1.__class__.__name__
print "\n===============================================1"


class EmptyClass:
pass

e1 = EmptyClass()

print "\n-------e1---------", e1
print "\n--------dir(e1)----------", dir(e1)
print "\n--------vars(e1)----------", vars(e1)
print "\n---------e1.__dict__-----------------", e1.__dict__
print "\n----------e1.__class__.__name__----------------", e1.__class__.__name__
print "\n-------isinstance(e1, EmptyClass)--------", isinstance(e1, EmptyClass)
print "\n-------isinstance(e1, MyClass)--------", isinstance(e1, MyClass)
print "\n===============================================2"

e1.__class__ = m1.__class__

print "\n-------e1---------", e1
print "\n--------dir(e1)----------", dir(e1)
print "\n--------vars(e1)----------", vars(e1)
print "\n---------e1.__dict__-----------------", e1.__dict__
print "\n----------e1.__class__.__name__----------------", e1.__class__.__name__
print "\n-------isinstance(e1, EmptyClass)--------", isinstance(e1, EmptyClass)
print "\n-------isinstance(e1, MyClass)--------", isinstance(e1, MyClass)
print "\n===============================================3"

e1.__dict__.update(m1.__dict__)

print "\n-------e1---------", e1
print "\n--------dir(e1)----------", dir(e1)
print "\n--------vars(e1)----------", vars(e1)
print "\n---------e1.__dict__-----------------", e1.__dict__
print "\n----------e1.__class__.__name__----------------", e1.__class__.__name__
print "\n-------isinstance(e1, EmptyClass)--------", isinstance(e1, EmptyClass)
print "\n-------isinstance(e1, MyClass)--------", isinstance(e1, MyClass)
print "\n===============================================4"



OUTPUT
=======
-------m1--------- <__main__.myclass>

--------dir(m1)---------- ['__doc__', '__init__', '__module__', 'amount', 'name', 'test']

--------vars(m1)---------- {'amount': 100, 'name': 'SAJU'}

---------m1.__dict__----------------- {'amount': 100, 'name': 'SAJU'}

----------m1.__class__.__name__---------------- MyClass

===============================================1

-------e1--------- <__main__.emptyclass>

--------dir(e1)---------- ['__doc__', '__module__']

--------vars(e1)---------- {}

---------e1.__dict__----------------- {}

----------e1.__class__.__name__---------------- EmptyClass

-------isinstance(e1, EmptyClass)-------- True

-------isinstance(e1, MyClass)-------- False

===============================================2

-------e1--------- <__main__.myclass>

--------dir(e1)---------- ['__doc__', '__init__', '__module__', 'test']

--------vars(e1)---------- {}

---------e1.__dict__----------------- {}

----------e1.__class__.__name__---------------- MyClass

-------isinstance(e1, EmptyClass)-------- False

-------isinstance(e1, MyClass)-------- True

===============================================3

-------e1--------- <__main__.myclass>

--------dir(e1)---------- ['__doc__', '__init__', '__module__', 'amount', 'name', 'test']

--------vars(e1)---------- {'amount': 100, 'name': 'SAJU'}

---------e1.__dict__----------------- {'amount': 100, 'name': 'SAJU'}

----------e1.__class__.__name__---------------- MyClass

-------isinstance(e1, EmptyClass)-------- False

-------isinstance(e1, MyClass)-------- True

===============================================4

python django howto class name as string

python django how to get class name of an object as string


>>> l = []
>>>
>>> l.__class__.__name__
'list'
===================
>>> t = ()
>>>
>>> t.__class__.__name__
'tuple'
===================
>>> d = {}
>>>
>>> d.__class__.__name__
'dict'
===================
>>> i = int(4)
>>>
>>> i
4
>>> i.__class__.__name__
'int'
===================
>>> f = float(4)
>>>
>>> f
4.0
>>>
>>> f.__class__.__name__
'float'
-------------------------
>>> class Test:
... pass
...
>>>
>>>
>>> t = Test()
>>>
>>> t.__class__.__name__
'Test'
===================

Friday, January 21, 2011

python django defining __getitem__ on a class

python django defining __getitem__ on a class

# defining __getitem__ on a class make it iterable in python?
# cb[0] is the same as cb.__getitem__(0)

#############################################1

class Test3:

Data = {'name':'saju', 'sex':'male'}

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1):
return self.Data[item1]


t3 = Test3()
print t3['name']
print t3['sex']


# OUTPUT
# ======
# ----in----__init__----
# saju
# male

#############################################2

class Test1:

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1):
print "-----in-----__getitem__-----", item1
if item1==5:
raise Exception('End')#For stop iteration (otherwise it will go to a loop)


t1 = Test1()

print "=============="

t1['saju'] #<----------IMP
t1.__getitem__('saju')

print "=============="
for x in t1:
pass

# OUTPUT
# ======
# ----in----__init__----
# ==============
# -----in-----__getitem__----- saju
# -----in-----__getitem__----- saju
# ==============
# -----in-----__getitem__----- 0
# -----in-----__getitem__----- 1
# -----in-----__getitem__----- 2
# -----in-----__getitem__----- 3
# -----in-----__getitem__----- 4
# -----in-----__getitem__----- 5
# Traceback (most recent call last):
# File "getitem.py", line 26, in
# for x in t1:
# File "getitem.py", line 15, in __getitem__
# raise Exception('End')#For stop iteration (otherwise it will go to a loop)
# Exception: End


#############################################3

class Test2:

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1, item2=0):
print "-----in-----__getitem__-----", item1, item2
if item1==5:
raise Exception('End')#For stop iteration (otherwise it will go to a loop)


t2 = Test2()

print "=============="

t2['saju'] #<----------IMP
t2.__getitem__('saju','1000')

print "=============="

for x in t2:
pass

# OUTPUT
# ======
# ----in----__init__----
# ==============
# -----in-----__getitem__----- saju 0
# -----in-----__getitem__----- saju 1000
# ==============
# -----in-----__getitem__----- 0 0
# -----in-----__getitem__----- 1 0
# -----in-----__getitem__----- 2 0
# -----in-----__getitem__----- 3 0
# -----in-----__getitem__----- 4 0
# -----in-----__getitem__----- 5 0
# Traceback (most recent call last):
# File "getitem.py", line 72, in
# for x in t2:
# File "getitem.py", line 60, in __getitem__
# raise Exception('End')#For stop iteration (otherwise it will go to a loop)
# Exception: End



#############################################