Showing posts with label concepts. Show all posts
Showing posts with label concepts. 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))

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

Wednesday, 10 July 2013

Datepicker - Multiple Forms on One Page

Having identically same form populated over one page.
DatePicker identify input elements via id, the following concept is to post-create new id before datepicker call.

$("input.calender").each(function(index, element){
    if($(element).hasClass("full")){
        var id = $(element).attr('id');
        $(element).attr('id', id+'_'+index);
        $(element).datepicker({
            dateFormat: "yy-mm-dd",
            changeYear: true,
            changeMonth: true
        });
    }
});

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

Wednesday, 29 May 2013

Python - Virtualenv Windows Wrapper

Install
pip install virtualenvwrapper-win
CMD
mkvirtualenv project_A
workon project_A
# Create New Virtualenv for each New Project

More Info: https://github.com/davidmarble/virtualenvwrapper-win/

Python - Dictionary to List with Key only

Dictionary
key_and_item = dict([(x,0) for x in range(10)])
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}

List
key_only = list(key_and_item)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# OrderedDict will also have the same effect

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

Tuesday, 21 May 2013

Python - Shortcut Conditional Expressions

If...Else Statement in one line

foo = 1
A = 'A'
B = 'B'
C = 'C'

x = A if foo > 0 else B
# A
 x = lambda: A if foo < 0 else B
x()
# B
x = A if not foo else B if foo < 0 else C
# C
Source: http://www.python.org/dev/peps/pep-0308/

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