пʼятниця, 10 грудня 2010 р.

Control over default music player from your application

If you need to control default music player from your application(in my case app which replace default lock screen) just make your activity implements MediaPlayerControl and impelement all of its methods.



public class MyActivity extends Activity implements MediaController.MediaPlayerControl
{

@Override
protected void onCreate(Bundle savedInstanceState){}


// implement all methods

@Override
public void start() { }

@Override
public void pause() { }
}

Custom Android Button Style

If you need to draw non standard button in android, you could do like described here:
http://blog.androgames.net/40/custom-button-style-and-theme/ . Very nice.
Or you could just do in your code, like that
   Button yourButton = (Button) findViewById(R.id.idForYourButton);
    yourButton.getBackground().setColorFilter(0xff00ffff, PorterDuff.Mode.MULTIPLY);
you could define color 0xff00ffff in your color.xml, and get it by R.color.your_color.

четвер, 2 грудня 2010 р.

Configure wsgi for Django on Apache

I was need to run old and new version of my site.
So how to configure 2 version of your project on one apache server?
I've used 2 ports: 80(default) and 8080.
Edit your /etc/apache2/ports.conf and add this lines
NameVirtualHost *:80
Listen 80
NameVirtualHost *:8080
Listen 8080

Then go to /etc/apache2/sites-enabled/ , edit @000-default(default) and add those lines:

<VirtualHost *:80>
ServerAdmin webmaster@{{your_domain}}
DocumentRoot /var/www/

WSGIScriptAlias / /{__path_to_dir_where_your_project_is__}/django.wsgi
WSGIDaemonProcess {name_of_process} user={user_name} group={group_name} processes=5 threads=1
WSGIProcessGroup {name_of_process}

<Directory "{__path_to_dir_where_your_project_is__}">
Order allow,deny
Allow from all
</Directory>

<Location "site_media">
SetHandler None
</Location>

Alias /site_media/ /{__path_to_dir_where_your_project_is__}/{__path_to_media_folder__}/
<Directory "{__path_to_dir_where_your_project_is__}/{__path_to_media_folder__}">
Options FollowSymLinks
AllowOverride None
Order allow,deny
allow from all

ExpiresActive On
ExpiresDefault "access plus 5 days"
</Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined

</VirtualHost>

<VirtualHost *:8080>
ServerAdmin webmaster@{{your_domain}}
DocumentRoot /var/www/
ServerName {{your_domain}}
WSGIScriptAlias / /{__path_to_dir_where_project_is(another_version)__}/django.wsgi
WSGIDaemonProcess {name_of_process} user={user_name} group={group_name} processes=5 threads=1
WSGIProcessGroup {name_of_process}

<Directory "{__path_to_dir_where_your_project_is(another_version)__}">
Order allow,deny
Allow from all
</Directory>

<Location "site_media">
SetHandler None
</Location>

Alias /site_media/ /{__path_to_dir_where_your_project_is(another_version)__}/{__path_to_media_folder__}/
<Directory "{__path_to_dir_where_your_project_is(another_version)__}/{__path_to_media_folder__}">
Options FollowSymLinks
AllowOverride None
Order allow,deny
allow from all

ExpiresActive On
ExpiresDefault "access plus 5 days"
</Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined
<VirtualHost>

and finaly create file django.wsgi in {__path_to_dir_where_your_project_is__} and {__path_to_dir_where_your_project_is(another_version)__}
Here it is:
#!/usr/bin/python
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = '{settings_file_of_your_project}'
sys.path.append('{__path_to_your_project__}')
sys.path.append('{__path_to_dir_where_your_project_is__}')

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Now you can start(restart) you apache.
Thats all folks!
p.s. it's work on my machine)

четвер, 23 вересня 2010 р.

js dynamic select with django

If you will need dynamic change of your select in your django templates than follow this post. There are 3 models: ItemType, SubItemType (this select depends from ItemType), Category(depends from SubItemType) and model Item with foreign key to those 3 ones.


models.py

class ItemType(models.Model):
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description

class SubItemType(models.Model):
    parent_itemtype = models.ForeignKey(ItemType, verbose_name="Parent type")
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description

class Category(models.Model):
    parent_subitemtype = models.ForeignKey(SubItemType, verbose_name="Parent SubType")
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description


class Item(models.Model):
    type = models.ForeignKey(ItemType, verbose_name="Type", null=True)
    other_type = models.CharField(max_length=128, null=True, verbose_name="Other type")

    sub_type = models.ForeignKey(SubItemType, verbose_name="Subtype", null=True)
    other_sub_type = models.CharField(max_length=128, null=True, verbose_name="Other subtype")

    category = models.ForeignKey(Category, verbose_name="Category", null=True)
    other_category = models.CharField(max_length=128, null=False, default='', verbose_name="Other category")


Usually we used something like this:


class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
but when we need some widgets(RadioButton etc) or when we need to specify some attributes for js(like "onchange", "style" etc) - we need to rewrite some fields of our model in forms.py as follows.
forms.py

class ItemForm(forms.ModelForm):   
    ITEM_TYPE_CHOICES = [('', 'others'), ] + [(str(t.id), t.description) for t in ItemType.objects.all()]
    SUB_ITEM_TYPE_CHOICES = [('', 'others), ] + [(t.id, t.description) for t in SubItemType.objects.all()]
    CATEGORY_TYPE_CHOICES = [('', 'others'), ] + [(t.id, t.description) for t in Category.objects.all()]
    type = forms.ChoiceField(label="Type", required=False,
            choices=ITEM_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'loadSubType(this);'}))

    sub_type = forms.ChoiceField(label="Subtype", required=False,
            choices=SUB_ITEM_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'loadCategory(this);'}))

    category = forms.ChoiceField(label="Category", required=False,
            choices=CATEGORY_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'showHideOtherCategory(this);'}))
    other_type = forms.CharField(label="", max_length=128, required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))
    other_sub_type = forms.CharField(label="", max_length=128,     required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))
    other_category = forms.CharField(label="", max_length=128, required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))

    class Meta:
        model = Item

    def clean_type(self):
        codice = self.data["type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return ItemType.objects.get(id=codice)
            except ItemType.DoesNotExist:
                raise ValidationError("Type %s doesn't exist" %codice)

    def clean_sub_type(self):
        codice = self.data["sub_type"]
        codice2 = self.data["type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return SubItemType.objects.get(id=codice, parent_itemtype=codice2)
            except SubItemType.DoesNotExist:
                raise ValidationError("SubType doesn't exist or doesn't fit Type selected above")

    def clean_category(self):
        codice = self.data["category"]
        codice2 = self.data["sub_type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return Category.objects.get(id=codice, parent_subitemtype=codice2)
            except Category.DoesNotExist:
                raise ValidationError("Category doesn't exist or doesn't fit SubType selected above")
functions clean_* are used for good-view django error validation.


In views.py there are some views used by our js-script for inserting in html < select > tags. We select needed data to dictionary var and then using simplejson we create json data and return it to our js-script.

views.py

def get_json_subtype(request, id):
    subitems=SubItemType.objects.filter(parent_itemtype=id)
    var={}
    temp1=""
    for s in subitems:
        temp1+=str(s.id)+" : '"+s.description+"', "
    var[id]="{"+temp1+"}"
    js_data = simplejson.dumps(var, ensure_ascii=False)
    # replacement of unnecessary characters
    # mb not so correct but it works for me
    js_data=js_data.replace('"{','{').replace('}"','}').replace(', }',' }');
    mimetype = 'application/javascript'
    return HttpResponse(js_data,mimetype)

def get_json_category(request, id):
    categories=Category.objects.filter(parent_subitemtype=id)
    var={}
    temp1=""
    for c in categories:
        temp1+=str(c.id)+" : '"+c.description+"', "
    var[id]="{"+temp1+"}"
    js_data = simplejson.dumps(var, ensure_ascii=False)
    js_data=js_data.replace('"{','{').replace('}"','}').replace(', }',' }');
    mimetype = 'application/javascript'
    return HttpResponse(js_data,mimetype)

Of course you can make one more universal function, instead of these two.

Then create some js-file in your media dir and put this code there.

function loadSubType(objSelect)
  {
      if(objSelect[objSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_type").style.display = "block";
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_sub_type").length=1;
          document.getElementById("id_category").length=1;
       }
      else
      {
          document.getElementById("id_other_type").style.display = "none";
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_other_type").value = "";

          var url="/get-json-subtype/"+objSelect[objSelect.selectedIndex].value;
          loadJsonData(objSelect, url, "id_sub_type");
       
      }
  }

function loadCategory(objectSelect)
  {
      if(objectSelect[objectSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_category").length=1;
       }
      else
      {
          document.getElementById("id_other_sub_type").style.display = "none";
          document.getElementById("id_other_sub_type").value = "";

          var url="/get-json-category/"+objectSelect[objectSelect.selectedIndex].value;
          loadJsonData(objectSelect, url, "id_category");
      }
  }

function showHideOtherCategory(objSelect)
  {
      if(objSelect[objSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_category").style.display = "block";
       }
    else
      {
          document.getElementById("id_other_category").style.display = "none";
          document.getElementById("id_other_category").value = "";
      }
  }

include this js-script to your template
<script type="text/javascript" src="/your_media_dir/your_script.js"></script>.

and finally your urls.py should include this:

    (r'^get-json-subtype/(\d+)/$', get_json_subtype),
    (r'^get-json-category/(\d+)/$', get_json_category),

Now when you choose some value from ItemType js-script will load values that you need to SubItemType select, and when you choose some value in SubItemType js will load values to Category select. And when you'll choose "others" in select box - an additional input field will appear under your select.

середа, 22 вересня 2010 р.

organize export to csv in django




If you will need to export some data from your model in django(here for example I used model Item).

Special attention to function smart_str which correct encode non-ascii symbols(if you use ukrainian, polish, italian, hindi etc).
Than in your template (html  file) put < a href=export-to-csv >export< /a >  or < form action="export-to-csv" >....< /form >
 in urls.py put this line:

(r'^export-to-csv/$', export_csv),

in views.py put this function:



from django.http import HttpResponse
from django.utils.encoding import smart_str
from models import Item
import datetime
import csv

def export_csv(request):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename="Data for " %s.csv' %datetime.datetime.now()
    writer = csv.writer(response)
    # Write headers to CSV file
    headers = []
    for field in Item._meta.fields:
        headers.append(field.verbose_name)
    writer.writerow(headers)
    # Write data to CSV file
    for obj in Item.objects.all():
        row=[]
        for field in Item._meta.fields:
            # Use smart_str for correct work of non-ascii symbols
            row.append(smart_str(getattr(obj, field.name)))
        writer.writerow(row)
    # Return CSV file to browser as download
    return response