Archive for the 'django' Category

23
Jan
12

unknown encoding: cp0


If you receive this when deploying django on apache, it’s because you have something like:


print "Something %s" % value

The fix is to change it to:


print "Something %s" % str(value)

28
Nov
11

django create superuser automatically on syncdb


Found the following information here. Here’s how you can automatically create a superuser when syncing your db:


python manage.py dumpdata auth > initial_data.json 
python manage.py syncdb

Make sure to modify the initial.json file, if you want to change the name/mail of the superuser.

21
Nov
11

always specify fields for django’s ModelForm as a tuple


So, I had a model that had a FileField called path, for which I wanted a ModelForm. Do not do this:


class MyModelForm(ModelForm):
   class Meta:
      model = MyModel
      fields= ("path")

It led to a strange error, saying django.core.exceptions.FieldError: Unknown field(s) (a, p, t, h). Of course, the fix was to specify the fields like:


class MyModelForm(ModelForm):
   class Meta:
      model = MyModel
      fields= ("path",)

21
Nov
11

django FileField and random names


To ensure that an uploaded file will have a random name, use a custom storage object, like described here.

03
Sep
11

django override widget to be used by field


I wanted to override the widget used by one of my fields, in the admin. Here’s how I ended up doing:



class MyAdmin(admin.ModelAdmin):
  def formfield_for_dbfield(self,db_field,**kwargs):
     field = super(MyAdmin,self).formfield_for_dbfield(db_field,**kwargs)
     if db_field.name == "name_of_field_i_want_to_override":
        field.widget = MyCustomWidget
     return field

03
Sep
11

django modelformset disallow empty forms


In order to disallow empty forms from being submitted to a ModelFormSet, do this in your formset:


class MyModelFormSet(BaseModelFormSet):
  def __init__(self,*args,**kwargs):
    super(MyModelFormSet,self).__init__(*args,**kwargs)
    for form in self.forms:
      form.empty_permitted = False

03
Sep
11

django acces instance used by admin


If you find that you need to access the instance used by the admin, override get_form in your ModelAdmin subclass:


class MyAdmin(admin.ModelAdmin):
  def get_form(self, request, obj=None, **kwargs):
    self.object_instance = obj
    return super(MyAdmin,self).get_form(request,obj,**kwargs)




Blog Stats

  • 216,805 hits