Monday, December 21, 2009

Source interface with Python and urllib2 - Stack Overflow

A monkey patch to change your source interface with python Source interface with Python and urllib2
import socket
true_socket = socket.socket
def bound_socket(*a, **k):
    sock = true_socket(*a, **k)
    sock.bind((sourceIP, 0))
    return sock
socket.socket = bound_socket

Tuesday, December 15, 2009

SplitSettings - Django

No sure why they don't set this up by default but the best way to setup your media and template paths is:
DIRNAME = os.path.abspath(os.path.dirname(__file__))
DATABASE_NAME = os.path.join(DIRNAME, 'project.db')
MEDIA_ROOT = os.path.join(DIRNAME,'media')
TEMPLATE_DIRS = (
    os.path.join(DIRNAME,'templates'),
)
SplitSettings - Django - Trac

Inlines support for Django generic views

Django generic views are missing one major feature, inline forms. This class is a drop in that adds the functionality. Wad of Stuff: Inlines support for Django generic views

Saturday, December 12, 2009

Lazy choices in Django form

A cool library that django has the doesn't seem to be documented very well
from django.utils.functional import lazy

class CarSearchForm(forms.Form):  
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
Lazy choices in Django form - Stack Overflow

Thursday, December 10, 2009

Python get IP of interface

Recipe 439094: get the IP address associated with a network interface (linux only)

Simple Python ping method

def ping(host):
    result = subprocess.call(["ping","-c","1",host],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    if result == 0:
        return True
    elif result == 1:
        raise Exception('Host not found')
    elif result == 2:
        raise Exception('Ping timed out')
useage:
try:
    ping('192.168.100.100')
except Exception:
    print "Ping error"
    raise

Friday, July 17, 2009

Foreign Key in Hidden Field

In order to have a hidden foreign key your in your form class you need to specify:
class PlanForm(forms.ModelForm):    
    owner = forms.ModelChoiceField(label="",queryset=Profile.objects.all(),widget=forms.HiddenInput())

Class definition order between two related classes

I ran into an issue where I wanted to have a foreign key to one class then over ride the save in the other class to update the current class. It would through and error because one of the classes was not defined. I finally found this post Class definition order between two related classes and see that you can but the models name in quotes in the foreign key. example:
class Foo(models.Model):
    bar = models.ForeignKey("Bar")
    name = models.CharField(max_length=100)

class Bar(models.Model):
    name = models.CharField(max_length=100)
    def save(self):
        foos = Foo.objects.filter(item=self)         
        foos.update(name=self.name)
        super(Bar, self).save()

Thursday, April 23, 2009

Django Custom Permissions ... sorta

There is no built in way to do row level permissions in Django, yet (see here) I have found a few hacks to get around this in the admin section. This is using 1.0.2 First add a Foreign key to the model this is an example models.py
from django.contrib.auth.models import User, Group
from django.db import models

class MyModel(models.Model):
   name = models.CharField(max_lenght=100)
   group = models.ForeignKey(Group)
Then in admin.py we need to override the queryset so that the user can only see objects that are part of his group and that he can only add objects that belong to his group
from django.contrib.auth.models import Group
from django.contrib import admin
from myproject.myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
   def __call__(self,request,url):
       self.request = request
       return super(DeviceAdmin, self).__call__(request,url)
   def formfield_for_dbfield(self, db_field, **kwargs):
       field = super(DeviceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
       if not self.request.user.is_superuser and db_field.name == 'group':
           my_choices = [('', '---------')]
           my_choices.extend(
               Group.objects.filter(
                   name__in=self.request.user.groups.all()
               ).values_list('id','name')
           ) # This can be one line it just doesn't fit
           print my_choices
           field.choices = my_choices
       return field
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            group_qs = Group.objects.filter(name__in=request.user.groups.all())
            return qs.filter(group__in=group_qs)

admin.site.register(MyModel,MyModelAdmin)
Now if you setup the admin in your settings and urls the groups for MyModel will only show up if the user belongs to that group. If the user is a super user they will see all the groups. If they user does not belong to any groups then they will not see any groups. Note: You can probably submit a post with the ID of a group that you do not belong to and it will work, I have not figured out how to add custom validation based on the request object yet. Here are some links that I used as a reference: http://stackoverflow.com/questions/430592/djang-admin-charfield-as-textarea http://www.djangosnippets.org/snippets/414/ http://code.djangoproject.com/ticket/3987#comment:32