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)
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)
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.
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",)
To ensure that an uploaded file will have a random name, use a custom storage object, like described here.
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
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
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)
An approach to generating custom JSON from your objects, mostly a repost of http://theoephraim.com/2011/04/json-encoding-custom-django-models/:
from django.utils.simplejson import JSONEncoder
class CustomObjectEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj,MyModel):
return obj.to_dict()
return JSONEncoder.default(self, obj)
class MyModel(models.Model):
# how our custom json will look like
def to_dict(self):
return {"id":self.id,"label":self.name,"value":self.name}
# view that generates json
def autocomplete(request):
mimetype = "application/javascript"
# need to call list, because querysets are not serializable
data = list(MyModel.objects.all())
return HttpResponse(CustomObjectEncoder().encode(data),mimetype)