Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Monday, 21 October 2013

Django - Loop Form Cleaned Data

for key, value in form.cleaned_data.iteritems():
    print key, value
Python 3
for key, value in form.cleaned_data.items():
    print (key, value)
Reference:
http://stackoverflow.com/questions/5904969/python-how-to-print-a-dictionarys-key

Django - Foreign Table Relational Mapping Queryset

def get_child_attribute_list(self, element):
    return Attribute.objects.filter(Q(element=element), Q(productattribute__product__parent=self)|Q(productattribute__product__root=self))

Thursday, 12 September 2013

Django - Site Matching Query Error

Site matching query does not exist. Lookup parameters were {'pk': 1}
Open Project Shell
python manage.py shell

Create Site Object
from django.contrib.sites.models import Site
Site.objects.create(pk=1, domain='example.com', name='example')
Best Practise
python manage.py syncdb --noinput
python manage.py migrate
python mange.py createsuperuser

Tuesday, 6 August 2013

Django - Combine Querysets into List

Combine QuerySets
result_list = sorted(chain(salary_item_list, salary_item_extra_list), key=attrgetter('created'))
Deduplicate
unique_results = [rows.next() for (key, rows) in groupby(result_list, key=attrgetter('created')]

Django - Queryset Extra Replace Annotate

Individual case for Annotate Replacement without using Raw
- OrderedDict required to use with select_params
- Sum amount based on different data type
- Concatenate texts of grouped result.
Reference for GROUP_CONCAT: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Reference for Extra: https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra

Tuesday, 23 July 2013

Heroku - Django Project Startup

settings.py
Troubleshooting for dj-static (In case static files error)
OSError: [Errno 2] No such file or directory: '/app/PROJECT_NAME/static'
heroku run python manage.py collectstatic --dry-run --noinput
wsgi.py
Procfile
runtime.txt
requirements.txt

Related Cmd

ssh-keygen -t rsa
# Generate ssh pub key (id_rsa)
ssh -v git@github.com
# Check your default .pub location for troubleshooting 
# Make sure both files included in the directory (id_rsa & id_rsa.pub)

heroku login
heroku keys
heroku keys:remove xxx@xxx

git init
echo local_settings.py>> .gitignore
# Remember to exclude local_settings.py in .gitignore
More info: https://devcenter.heroku.com/articles/gitignore
git add .
git commit -m 'Initial commit'

git remote -v
git remote rm heroku
More info: https://devcenter.heroku.com/articles/git

heroku create APP_NAME OR heroku git:remote -a EXISTING_APP_NAME

git push heroku master

heroku addons | grep POSTGRES
heroku addons:add heroku-postgresql:dev
heroku pg:wait
heroku config | grep HEROKU_POSTGRESQL
heroku pg:promote HEROKU_POSTGRESQL_XXX_URL
# Replace XXX with info from heroku config
More info: https://devcenter.heroku.com/articles/heroku-postgresql

heroku open

heroku run python manage.py syncdb
heroku run python manage.py migrate APP
heroku run python manage.py shell

More info: https://devcenter.heroku.com/articles/django

Monday, 15 July 2013

Django - Clone Fields to Related Model

Clone fields from OwnerProfile to PurchaseProfile
exclusion_list = ['id', 'created']
profile_list = PurchaseProfile.objects.filter(
reference_content_type=ContentType.objects.get_for_model(model), reference_object_id=self.pk)
profile_field_list = profile_list[0]._meta.get_all_field_names()
reference_data = dict([(field.name, getattr(self, field.name)) for field in self._meta.fields if field.name not in exclusion_list and field.name in profile_field_list])
profile_list.update(**reference_data)

Thursday, 11 July 2013

Django - Redirect with GET Query String

response =  redirect('salary_payment_list')
response['Location'] += '?type=unpaid'
return response

Saturday, 1 June 2013

Django - Static Directory Index

urls.py
from django.conf import settings
....
if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^static_0/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATICFILES_DIRS[0], 'show_indexes': True}),
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    )
....



More Infohttps://docs.djangoproject.com/en/1.2/howto/static-files/#directory-listings

Thursday, 30 May 2013

Django - Access HttpRequest from Template

settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    ....
    'django.core.context_processors.request', # not enabled by default
    ....
)
template.html
{{ request.GET.foo }} {{ request.COOKIES }} {{ request.META }} {{  request.user }}
# To access current HttpRequest's attributes & methods

More Info:
https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
https://code.djangoproject.com/wiki/HttpRequest

Tuesday, 28 May 2013

Django - Run Multiple Django Simultaneously

Edit - drivers\etc\hosts
127.0.0.1       local.project-a.com
127.0.0.1       local.project-b.com

Project A
1. cmd
  python manage.py runserver 8080

2. web browser

  http://local.project-a.com:8080

3. cookies check
 

Project B
1. cmd
  python manage.py runserver 8888

2. web browser

  http://local.project-b.com:8888

3. cookies check

Monday, 27 May 2013

Django - Select Related & Prefetch Related ORM Optimization


Initial
Sales.objects.filter(sales_person=self)

Select Related (O2O)
Sales.objects.select_related().filter(sales_person=self)

Prefetch Related (M2M / M2O)
Sales.objects.select_related().prefetch_related('booking_set', 'advancepayment_set', 'others_set').filter(sales_person=self)

More info:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

Django - Direct Foreign Key Optimization


No Query Execute
sales.customer_pk

Query Executed
sales.customer or sales.customer.pk

*Not working on Reverse Foreign Key, checking the instance properties by using dir(sales)

Source: https://docs.djangoproject.com/en/1.4/topics/db/optimization/#use-foreign-key-values-directly

Sunday, 26 May 2013

Django - External Debugger

Requirements (Choose one)
A. Install into site-packages
pip install django-debug-toolbar
pip install django-extensions
pip install Werkzeug

B. Download and put it all together into a directory
pip install --download="DEBUG" --no-install django-debug-toolbar django-extensions Werkzeug six
Reference: http://www.pip-installer.org/en/latest/cookbook.html
# After download then extract accordingly as following

Directory Tree
Projects
+---My_Project1
|   +---...
|
+---My_Project2
|   +---...
|
+---My_Project3
|   +---...
|
+---DEBUG
|   +---debug_toolbar
|   |   +---...
|
|   +---django_extensions
|   |   +---...
|
|   +---werkzeug
|   |   +---...
|
\---six.py
# I'm using method B.
local_settings.py
import os
import sys

from settings import MIDDLEWARE_CLASSES, INSTALLED_APPS

DEBUG_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../DEBUG').replace('\\','/')
if os.path.exists(DEBUG_DIR):
     sys.path.append(DEBUG_DIR)
     MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
     INSTALLED_APPS += ('debug_toolbar', 'django_extensions',)
     INTERNAL_IPS = ('127.0.0.1',)
     DEBUG_TOOLBAR_CONFIG = {
       'INTERCEPT_REDIRECTS': False,
     }

Source Files:
https://github.com/django-debug-toolbar/django-debug-toolbar
https://github.com/django-extensions/django-extensions
https://github.com/mitsuhiko/werkzeug
https://pypi.python.org/pypi/six # For django-extensions

Tuesday, 14 May 2013

Django - Get Distinct Data of a Proxy Model

models.py
class SalesPerson(User):
    class Meta:
        proxy = True
    ....

class SalesManager(models.Manager):
    def get_sales_person_list(self, user):
        if user.is_superuser:
            return list(SalesPerson.objects.filter(
                pk__in=list(Sales.objects.values_list('sales_person', flat=True)
                .order_by("sales_person").distinct())))

class Sales(CommonModel):
    ....
    sales_person = models.ForeignKey(User, related_name="sales_by")
    ....
    objects = SalesManager()
    ....
History - Before Optimized
return [SalesPerson.objects.get(pk=obj) for obj in self.get_query_set()
            .values_list('sales_person', flat=True).order_by("sales_person").distinct()] 

Django - Drop Down List Data Refresh/Reload

forms.py
INITIAL_CHOICE = ('', '---------')
class ProfileForm(forms.Form):
    profile_id = forms.ChoiceField(label=_('Profile'), choices=[INITIAL_CHOICE])
 
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields["profile_id"].choices = [INITIAL_CHOICE]+[(obj.id, "%s [%s]" % (obj.name, obj.identity,)) for obj in Profile.objects.all()]
 

Sunday, 12 May 2013

Django - Extra to Calculate Grand Total

Sales.objects.extra(select={
            'grand_total': "cost_foo_1 + cost_foo_2 + cost_foo_3"
        }, where=['id=%s'], params=[self.pk])[0].grand_total

Django - Models.Field Blank & Null

Blank
* django: not required field on forms & db
* db: store as ''
* data type: Text/Char fields (Empty string will be stored as '')
text_field = models.CharField(max_length=50, blank=True)

Null
* django: not required field on db only
* db: store as NULL
* data type: Non-string fields (Integers, Booleans and Dates)
date_field = models.DateField(blank=True, null=True)

Foreignkey
user = models.ForeignKey(User, blank=True, null=True)

Source: https://docs.djangoproject.com/en/dev/ref/models/fields/

Django - Override Abstract Model Fields

models.py

class Payment(CommonModel):
"""Payment info"""
....
class Meta:
    abstract = True

class AdvancePayment(Payment):
"""Advance Payment info"""
....
AdvancePayment._meta.get_field('foo').blank = TrueAdvancePayment._meta.get_field('foo').null = True

Special case
 ? The field 'AdvancePayment.foo' does not have a default specified, yet is NOT NULL.
 ? Since you are making this field nullable, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ?  1. Quit now, and add a default to the field in models.py
 ?  2. Specify a one-off value to use for existing columns now
 ?  3. Disable the backwards migration by raising an exception.
 ? Please select a choice: 2
 ? Please enter Python code for your one-off default value.
 ? The datetime module is available, so you can do e.g. datetime.date.today()
 >>> ''

 South generated migration (Changes for backwards compatibility)

def backwards(self, orm):
....
db.alter_column('sales_advancepayment', 'foo', self.gf('django.db.models.fields.DateField')(default=''))

change to

db.alter_column('sales_advancepayment', 'foo', self.gf('django.db.models.fields.DateField')(null=False, blank=False))