Saturday, 27 July 2013

Save file from memory to disk in django

Get file from memory and save into temp directory of OS in django

This article basically for saving the file from memory to temporary directory in django.

Here is the sample code.

from import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
def upload_excel_file(request):
    data = request.FILES['file']
    path ='tmp/' + str(data), ContentFile(
    tmp_file_path = os.path.join(settings.MEDIA_ROOT, path)

Now this tmp_file_path is the path of your file which is now saved into tmp directory of OS.

Thursday, 18 July 2013

Implementation of PUT and DELETE in pycurl

Implementation of PUT and DELETE in pycurl

Through this post explaining about the usage of PUT and DELETE in pycurl.

import pycurl
import json

Here is the sample example of curl which is using PUT and DELETE
curl -XPUT localhost:9200/tweets/tweet/1 -d '
user: "Test User",
message: "Test Message",
postDate: "20130201T02:00:00",
"mappings" : {
    "tweet" : {
        "_source" : {"enabled" : false}

curl -XDELETE 'http://localhost:9200/twitter/tweet/1'
page_index = {
user: "Test User",
message: "Test Message",
postDate: "20130201T02:00:00",
"mappings" : {
    "tweet" : {
        "_source" : {"enabled" : false}

c = pycurl.Curl()
# Remove Index if alreday exists
c.setopt(pycurl.URL, "http://localhost:9200/twitter")
c.setopt(pycurl.CUSTOMREQUEST, "DELETE")
# Create new index
c.setopt(pycurl.URL, "http://localhost:9200/twitter")
c.setopt(pycurl.CUSTOMREQUEST, "PUT")
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, '%s' % json.dumps(page_index ))

Wednesday, 10 July 2013

Create readonly permission for all models - Django

Create read only permission for all models - Django

Is it possible to create readonly /viewonly permission for all models in django. If admin provide read only permission to a particular user, an user can't edit record and can view only. So here is a very simple code for the same. Created an app and have the following features:
  • If user have a permission to view only, user cant edit record or in others word can only view.
  • Submit row will disappear, as an user dont have any benefits for - Save, Save & Continue, Save & Add buttons.
Follow these steps.
a. Create an app with the name of 'admin_hack' by this command -
"python startapp admin_hack" This will create following files.
b. Rename >>
c. Write following code to file
from django.contrib import admin
from django.db.models.signals import post_syncdb
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.util import flatten_fieldsets
from django.contrib.admin.templatetags.admin_modify import *
from django.contrib.admin.templatetags.admin_modify import submit_row as original_submit_row
def add_cannot_edit_record_permission(sender, **kwargs):
    This syncdb hooks takes care of adding a view permission to all our
    content types.
    for content_type in ContentType.objects.all():
        codename = "cannot_edit_record_for_%s" % content_type.model

        if not Permission.objects.filter(content_type=content_type, codename=codename):
                name="Cannot edit record for %s" %
class HackAdminModel(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        """Get readonly fields.

        :param request: HTTP request object.
        :param obj: An object.
        :return: Return readonly fields.
        class_name = self.__class__.__name__.replace('Admin', '').lower()

        for permission in request.user.get_all_permissions():
            head, sep, tail = permission.partition('.')
            perm = "cannot_edit_record_for_%s" % (class_name)
            if str(perm) == str(tail):
                if request.user.has_perm(str(permission)) and not request.user.is_superuser:
                    if self.declared_fieldsets:
                        return flatten_fieldsets(self.declared_fieldsets)
                        return list(set(
                            [ for field in self.opts.local_fields] +
                            [ for field in self.opts.local_many_to_many]
        return self.readonly_fields

    @register.inclusion_tag('admin/submit_line.html', takes_context=True)
    def submit_row(context):
        """Sumbit row.

        :param context: Dictionary of required data.
        :return: Return update context.
        ctx = original_submit_row(context)
        app_name, seprator, model_name = str(context.dicts[0]['opts']).partition('.')

        for permission in context['request'].user.get_all_permissions():
            head, sep, tail = permission.partition('.')
            perm = "cannot_edit_record_for_%s" % (model_name)
            if str(perm) == str(tail):
                if context['request'].user.has_perm(str(permission)) and \
                        not context['request'].user.is_superuser:
                        'show_save_and_add_another': False,
                        'show_save_and_continue': False,
                        'show_save': False,
                return ctx
        return ctx
d. Add following code to file
from admin_hack import *
e. Now go to your file and add this app to "INSTALLED_APPS"  like this
NOTE: Add this app i.e 'admin_hack' at the top of other created apps.
Now your app is ready to use.
Now question raise, how to use this app for all models. Using an example, going to use this app i.e admin_hack.
Here in the installed apps there is an app after admin_hack i.e 'pages'. I am gonna use this app for pages
Follow these steps:
a.  Go to the file of this app and import 'admin_hack' like this
# Hack Model
from admin_hack.admin_hack import HackAdminModel
b. Pass this 'HackAdminModel' to admin class like this
class PagesAdmin(HackAdminModel)
Before passing HackAdminModel the class PagesAdmin was like 
class PagesAdmin(admin.ModelAdmin) 
Now run following command to create permissions - "python syncdb" 
Testing of Admin Hack App
Now login to the admin site and view permissions. Permissions created for all models with the 
name as"Cannot edit record for '*' (* - signifies model name)
NOTE: This permission will work only for those models if you  pass 'HackAdminModel' 
to class ModelAdmin(admin.ModelAdmin) like this class ModelAdmin(HackAdminModel)

Code is on git hub and can download, here is the link:

Monday, 8 July 2013

Install pyCurl

Install pyCurl in your virtual environment


An issue is coming while installing pyCurl to virtualenv so here is the solution for the same.

By following these steps, its possible to overcome from this problem

Here we gooo..........

(pyenv)anupam@anupampc:~/workspace/rocksocialrest$ pip install pycurl
Downloading/unpacking pycurl
  Downloading pycurl-7.19.0.tar.gz (71kB): 71kB downloaded
  Running egg_info for package pycurl
    sh: 1: curl-config: not found
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/home/anupam/workspace/rocksocialrest/pyenv/build/pycurl/", line 90, in <module>
        raise Exception, ("`%s' not found -- please install the libcurl development files" % CURL_CONFIG)
    Exception: `curl-config' not found -- please install the libcurl development files
    Complete output from command python egg_info:
    sh: 1: curl-config: not found

Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/home/anupam/workspace/rocksocialrest/pyenv/build/pycurl/", line 90, in <module>

    raise Exception, ("`%s' not found -- please install the libcurl development files" % CURL_CONFIG)

Exception: `curl-config' not found -- please install the libcurl development files

Command python egg_info failed with error code 1 in /home/anupam/workspace/rocksocialrest/pyenv/build/pycurl
Storing complete log in /home/anupam/.pip/pip.log

(pyenv)anupam@anupampc:~/workspace/rocksocialrest$ apt-cache depends python-pycurl
  Depends: libc6
  Depends: libcurl3-gnutls
  Depends: libgcrypt11
  Depends: python2.7
  Depends: python
  Depends: python
  Suggests: libcurl4-gnutls-dev
  Suggests: python-pycurl-dbg
  Conflicts: <python2.3-pycurl>
  Conflicts: <python2.3-pycurl:i386>
  Conflicts: <python2.4-pycurl>
  Conflicts: <python2.4-pycurl:i386>
  Replaces: <python2.3-pycurl>
  Replaces: <python2.3-pycurl:i386>
  Replaces: <python2.4-pycurl>
  Replaces: <python2.4-pycurl:i386>
  Conflicts: python-pycurl:i386 

(pyenv)anupam@anupampc:~/workspace/rocksocialrest$ sudo apt-get install libcurl4-gnutls-dev

then pip install pycurl