Django Admin Site Namespace Reverse URLS

I was having an odd issue where {% url ‘custom_admin:foo_bar_changelist’ %} would work from one admin but not another location. I put it on Stack Overflow… got an answer that one can manually construct the adminsite include via include(adminsite.get_urls(), ‘app_name’, ‘namespace’).

http://stackoverflow.com/questions/17706548/django-multiple-adminsite-noreversematch-from-second-adminsite-instance/17707090?noredirect=1#comment25845627_17707090

Shopify API SSL Requirement

Got an error suddenly starting in the past 2 days (2013) that my API connection failed due to “SSL Required”.

{"errors":"SSL required"}

This exact error means you need to use HTTPS in your api requests.

Broke at a critical time for us.

DataTables – fnFilter match blank space regexp

Wow, I had to dig into the source of DataTables 1.9.3 to figure out why a regular expression with no “smart filter” was failing.

Turns out each column is returning massively padded data due to the HTML blocks containing spaces.

Trim it to match regexps that rely on position like ^$ (blank) or .+ (1+). Those extra leading/trailing whitespace chars are the problem.

Go to the DataTables source… look at this function and trim whitespace from sData:

Note that there may be an API for overriding internal functions… but I can’t be bothered to look right now. This has been a long debug.

		 */
		function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart, bCaseInsensitive )
		{
			if ( sInput === "" )
			{
				return;
			}
			
			var iIndexCorrector = 0;
			var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive );
			for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- )
			{
				var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ),
					oSettings.aoColumns[iColumn].sType );
				if ( ! rpSearch.test( sData.trim() ) ) ////////// add .trim() here

Django — Prevent ModelForm from updating values if user did not submit them

I have a model that is being shared across many different forms. An ugly side effect of this was that if I ever forgot to ensure that the HTML rendered contained *exactly* the fields defined in the form, django would overwrite the values.

Here’s a mixin that you can add to any ModelForm which will only update values.

Note that this still allows users to update a model field explicitly with a blank.

from django.forms.models import model_to_dict
from django import forms
 
 
class OverwriteOnlyModelFormMixin(object):
    '''
    Delete POST keys that were not actually found in the POST dict
    to prevent accidental overwriting of fields due to missing POST data.
    '''
    def clean(self):
        cleaned_data = super(OverwriteOnlyModelFormMixin, self).clean()
 
        for field in cleaned_data.keys():
            if self.prefix is not None:
                post_key = '-'.join((self.prefix, field))
            else:
                post_key = field
 
            if post_key not in self.data:
                # value was not posted, thus it should not overwrite any data.
                del cleaned_data[field]
 
        # only overwrite keys that were actually submitted via POST.
        model_data = model_to_dict(self.instance)
        model_data.update(cleaned_data)
        return model_data

Increase upload size on WordPress DreamHost

This is stupid.

All htaccess, php.ini, define_ methods failed.

This is what works:

Download this
http://sxi.sabrextreme.com/phpini

Put it on your server.

Go to it with your browser.

Click install.

Navigate to the mywordpress.com/cgi-bin folder and edit php.ini

Find max_upload_size and modify to whatever you want.
find max_post_size and modify to whatever you want.

This is stupid.

Django Form field in Initial Data: requires a FieldFile instance

I just followed the source back from django’s ClearableFileInput all the way to django’s model field magic… all the way to a little thing called FieldFile.

FieldFile can be faked with these minimum attributes:

from django.core.files.storage import default_storage

class FakeField(object):
    storage = default_storage

fieldfile = FieldFile(None, FakeField, file_path)

form = SomeForm(initial={'filefield': fieldfile })

WHEW!

Django DatabaseError invalid byte sequence for encoding “UTF8”

Wow this debugging lead me nowhere.

invalid byte sequence for encoding “UTF8”:
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by “client_encoding”.

If you’re getting a DatabaseError, double check that you are not trying to store pickled data through the ORM. The python docs are wrong about pickle protocol 0 being ASCII only and pickle.dumps(u’©∆∂ƒ©˙∆˚’) will output non ASCII.

bug tracked here: http://bugs.python.org/issue2980

Causing a tough to track error at the DB level which does not consistently appear until a “bad” string is passed in.

Python Profiler on Ubuntu Missing or import hotshots.stats fail

Turns out Ubuntu is missing pythons standard library component profile.py due to licensing issues related to debian.

I don’t really care about that.

What I care about is the solution.

Enable the multiverse repository in your ubuntu.

vim /etc/apt/sources.list

Copy and paste one of the lines (they are version specific) and replace the ending text with “multiverse”. It doesn’t really do any damage to keep other repo names on there.

## Added mutliverse for python-profiler
deb http://us.archive.ubuntu.com/ubuntu/ lucid multiverse

Update repo list and install python-profiler.

apt-get update
apt-get install python-profiler

Done.