Category: Django

Install Celery 3.1.25 in Django 1.10 with Ubuntu 16.04 Production

Install Celery 3.1.25 in Django 1.10 with Ubuntu 16.04 Production

Celery is awesome tools to manage queue in Django. It’s can reduce processing time in serial / sync process. For instance, we have schema for registering user: 1. User click on Sign-up Button 2. We create and save into records (1 second) 3. Signals trigger send SMS to User (1 second) 4. Signals trigger send …

+ Read More

Open Permission access custom for Django Rest Framework

Open Permission access custom for Django Rest Framework

When we need to open access for API Django-restframework, we can do it by extending the permission class. Here is some example: 123456789101112131415161718192021class PublicUserPermissions(permissions.BasePermission):     """     Granting public access permissions     """     def has_object_permission(self, request, view, obj):         # Allow get requests for all     …

+ Read More

Solve integrity error duplicate key in Django PostgreSQL

Solve integrity error duplicate key in Django PostgreSQL

This error caused by we’re using database from copy / clone database. The sequences will be mixed-up. To solved this, just follow this way : 12python manage.py sqlsequencereset <app-name> > app.sql psql -U username -d database -a -f < app.sql Then your problem shall gone!

Setup Ubuntu Server in Softlayer for Django

Setup Ubuntu Server in Softlayer for Django

Here are a quick step to setup Ubuntu server in Softlayer for Django 1. Install depedencies 1234apt-get install python-software-properties software-properties-common add-apt-repository ppa:webupd8team/java apt-get update sudo apt-get install oracle-java7-installer 2. Install UWSGI, Python, PostgreSQL and other modules 1sudo apt-get install libpq-dev python-dev python-software-properties postgresql postgresql-contrib nginx git zip unzip build-essential python nmap libxslt1-dev python-pip imagemagick uwsgi …

+ Read More

JqGrid inline editing integration with DJango send csrf token

JqGrid inline editing integration with DJango send csrf token

Here is a quick snippet to send csrf_token in POST data from inline edit JqGrid to Django: 12345678910111213141516var tableGrid = $(selector).jqGrid({    ….    onSelectRow: function(id){          if(id && id!==lastSel){             $(selector).restoreRow(lastSel);             lastSel=id;          }       …

+ Read More

Handle error form.save() with model validation

Handle error form.save() with model validation

Here is a quick snippet to avoid form.save() error because model validation : 12345678# handle form save with model validationerror # http://stackoverflow.com/questions/8771029/django-raise-a-validation-error-in-a-models-save-method try:     form.save() except ValidationError, e:     form._errors = {}     for _, v in e.message_dict.items():         form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v)

JqGrid delete multiple select rows

JqGrid delete multiple select rows

There is an issue if we delete rows using : 12345678910// Get all selected row var rows = $(selector).jqGrid("getGridParam", "selarrrow"); console.log(rows); // Iterate and delete for (var i in rows) {       console.log(i);       console.log(rows[i]);       $(selector).jqGrid(‘delRowData’, rows[i]); } Only a few records will deleted. The solution : 12345678910111213/** …

+ Read More

Save django model with dictionaries

Save django model with dictionaries

Beware when queryset filter update() because it will pass model validation. Here is some example save model with dictionaries : 12345678910for k, v in account.items():     setattr(instance, k, v) try:     instance.save() except Exception, e:     raise ValidationError(e) else:     updated += 1     # print account

Modify object data by write Custom Renderer in Django Rest Framework

Modify object data by write Custom Renderer in Django Rest Framework

When we need to modify object or results from DRF / Django Rest Framework, all we need just write a custom JSON Renderer like below : 1234567891011121314class JGridJSONRenderer(renderers.JSONRenderer):     def render(self, data, accepted_media_type=None, renderer_context=None):         new_rows = []         # Name the object list         …

+ Read More

Django unit test formset

Django unit test formset

When testing page that contains formset in Django using unit test, we may encounter : 1ValidationError: [u’ManagementForm data is missing or has been tampered with’] This is happend because we POST data without required FORMSET hidden value in form. To solve this issue, inspect element on your formset and insert hidden value in payload data. …

+ Read More

Django check related model and check field if exists in model

Django check related model and check field if exists in model

We can check if the field is related model in Model by : 1model._meta.get_field("name_of_field").get_internal_type() == "ForeignKey" Then we can check if the field name is exists in model by : 1model._meta.get_field_by_name(_name) Some example code: 123456789101112131415if self.model._meta.get_field(field_name).get_internal_type() == "ForeignKey":     # get related model     # http://stackoverflow.com/questions/10347210/django-foreign-key-get-related-model     related_model = self.model._meta.get_field(field_name).rel.to     …

+ Read More

Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.

Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.

I got this problem: 123456λ git status On branch master Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.   (use "git pull" to merge the remote branch into yours) nothing to commit, working directory clean Solution 12λ git reset –hard origin/master HEAD is now at 63813ef fix localdb

Git checkout track from remote branch

Git checkout track from remote branch

Let’s say somebody already push their branch in remote called “finances”. We want to fetch and working on this branch from our local. So, the solution : 12345git fetch –all Fetching origin From github.com:polatic/vasham-erp  * [new branch]      finance    -> origin/finance Then, we checkout with tracking 123git checkout -t origin/finance Branch finance set …

+ Read More

Accelerate django development server with django-devserver

Accelerate django development server with django-devserver

As we know what django development server running on single thread. This is make development a bit slow. There is some alternative, by using django-devserver Here is the quickstep: 1. Install the app 1pip install git+git://github.com/nealtodd/django-devserver 2. Edit your local_settings.py 12345INSTALLED_APPS =  (‘devserver’,) + INSTALLED_APPS MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + (    ‘devserver.middleware.DevServerMiddleware’, ) 3. Then …

+ Read More

Solve Django Filter queryset result duplicates with Pagination

Solve Django Filter queryset result duplicates with Pagination

When we filter using multiple filter and mixed with django pagination, somehow the results are duplicates. This is incorrect. Apparently, looking at the source code https://github.com/alex/django-filter/blob/master/django_filters/filters.py#L105, I found this line: 1234q = Q() for v in value:     q |= Q(**{self.name: v}) return qs.filter(q).distinct() By default, django-filter not using “AND” condition and that’s why …

+ Read More

Setup Django and Timezone follow server datetime (Ubuntu)

Setup Django and Timezone follow server datetime (Ubuntu)

Here is quickfix to setup Django working with server timezone. 1. Set Server Timezone Check by : 12date Mon Jan  5 10:54:38 WIB 2015 If this not correct or you want to change server timezone, then edit “/etc/timezone” 1Asia/Jakarta Then do : 12sudo dpkg-reconfigure –frontend noninteractive tzdata date Now you should see the updated server …

+ Read More

Django django-admin.py startproject ImportError

Django django-admin.py startproject ImportError

Suddenly i got this error in Windows when trying to start a new Django project : 1django-admin.py startproject ImportError: No module named django.core The solution : 1python C:\Python27\Scripts\django-admin.py startproject example

Celery as daemon service in Ubuntu for production

Celery as daemon service in Ubuntu for production

Here is a quickstep to set Celery as daemon in Ubuntu 14.04 for production: Create file “/etc/init.d/celeryd” : 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395#!/bin/sh -e # ============================================ #  celeryd – Starts the Celery worker daemon. # ============================================ # # :Usage: /etc/init.d/celeryd {start|stop|force-reload|restart|try-restart|status} # :Configuration file: /etc/default/celeryd # # See http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html#generic-init-scripts ### BEGIN INIT INFO # Provides:         …

+ Read More

Install Django in Windows 8 / 7

Install Django in Windows 8 / 7

Here is quick step to setup Django in windows box : 1. Install Python Please download https://www.python.org/ftp/python/2.7.7/python-2.7.7.msi. 2. Install Setuptools http://www.lfd.uci.edu/~gohlke/pythonlibs/4jci5y59/setuptools-5.8.win32-py2.7.exe 3. Install PIP http://www.lfd.uci.edu/~gohlke/pythonlibs/4jci5y59/pip-1.5.6.win32-py2.7.exe 4.Don’t forget to set global environment variables (depend on your Python path installation) In PATH, please add : 1C:\Python27\;C:\Python27\Scripts;C:\Python27\Lib\site-packages\django\bin; 5. Install Django 1pip install django 6. Create new django project …

+ Read More

Configure Django Celery, RabbitMQ in Windows and periodic task

Configure Django Celery, RabbitMQ in Windows and periodic task

Here is guide to setup Django, Celery, RabbitMQ in Windows and running periodic task. 1. Install RabbitMQ Go to http://www.rabbitmq.com/download.html, install and check if the services already running 2. Setup celery in your Django Project Install django-celery modules 1pip install django-celery 3. Example configuration for periodic task In this example, i create tasks.py in app …

+ Read More

Setup Queue in Django using Celery and RabbitMQ

Setup Queue in Django using Celery and RabbitMQ

I’m using Ubuntu for setup queue in Django using celery and rabbitmq. Go to console and we need to install rabbitmq at first: 1. RabbitMQ 1234wget http://www.rabbitmq.com/rabbitmq-signing-key-public.asc sudo apt-key add rabbitmq-signing-key-public.asc sudo apt-get update sudo apt-get install rabbitmq-server To adjust system limits (in particular the number of open file handles), edit the file /etc/default/rabbitmq-server to …

+ Read More

TypeError: __init__() got an unexpected keyword argument ‘preserve_default’

TypeError: __init__() got an unexpected keyword argument ‘preserve_default’

Quickfix to solve ; 12345678    migration_module = import_module("%s.%s" % (module_name, migration_name))   File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module     __import__(name)   File "D:\Python\vasham\dashboards\migrations\0004_auto_20141112_1644.py", line 7, in <module>     class Migration(migrations.Migration):   File "D:\Python\vasham\dashboards\migrations\0004_auto_20141112_1644.py", line 18, in Migration     preserve_default=True, TypeError: __init__() got an unexpected keyword argument ‘preserve_default’ Is 1pip install django …

+ Read More

No python application found, check your startup logs for errors

No python application found, check your startup logs for errors

This errors occured in setup Django + UWSGI in Ubuntu 14.04. The reason because the uwsgi from aptitude is broken. 1234Sat Oct 25 12:38:28 2014 – — no python application found, check your startup logs for errors — [pid: 5556|app: -1|req: -1/1] 36.78.164.116 () {42 vars in 681 bytes} [Sat Oct 25 12:38:28 2014] GET …

+ Read More

Django UWSGI Ubuntu 14.04 in Amazon EC2

Django UWSGI Ubuntu 14.04 in Amazon EC2

Here is complete tutorial installing and setup django for production in EC2 Ubuntu 14.04. First, we need to login into EC2, setup a new instance and launch. Then login SSH and ready for action. 1. Always get latest updates 1sudo apt-get update && sudo apt-get upgrade -y 2. Install Java 1234sudo apt-get install python-software-properties sudo …

+ Read More

Remove dash or empty label in Django Form ForeignKey

Remove dash or empty label in Django Form ForeignKey

To remove dash or empty selection in form foreignkey Django, we just need to declare “empty_label=None” in the form. Here is the example : 1234instance = forms.ModelChoiceField(empty_label=None,                 queryset=Instance.objects.exclude(                    …some queryset..                 …

+ Read More