March 7, 2013

Django – URL for Editing a Model

I’m learning Python and Django. So far so good but I ran into some trouble today and couldn’t find what I was looking for. In my template, I was trying to construct the URL to the admin view for editing a model. Finally I found the answer and thought I’d share it:

My model:

class Foo(models.Model):
    def get_admin_url(self):
        return urlresolvers.reverse("admin:%s_%s_change" % (self._meta.app_label, self._meta.module_name), args=(self.id,))

And then in my template I can reference the function on my model:

...
<td><a href="{{ c.get_admin_url }}">Edit</a></td>
...

If you need to link to any other admin views for that model, refer to the Django documentation and just change the value passed to urlresolves.reverse.

February 23, 2013

Javascript Closures

I thought I’d take a moment to share my Javascript Closure template which I use regularly. Its a great way to namespace your functions and encapsulate functionality into packages. This is another helpful resource if you want to learn more about why we do it.

ProTip: If you’re a Visual Studio developer, this code snippet may save you a little time. Just change the suffix to .snippet and store in your code snippets folder.

var Namespace = function () {

    return {

        Init: function () {
            //if anything needs to be inited, it can be done here
        },

        PublicFunction: function (args) {

            //Need fully qualify function when calling
            //a from within the namespace
            Namespace.AnotherPublicFunction(args);

            //fully qualified not needed for private functions
            _privateFunction(args);

        },

        AnotherPublicFunction: function(args){
        }
    };

    function _privateFunction : function(args){
    }
} ();
August 10, 2012

Javascript Namespacing

I’ve written before about javascript closures which are incredibly helpful and very tidy once you understand what they’re doing. However, I have some a new code template I use when namespacing my javascript libraries. First rule of thumb is to never pollute the global namespace; you should always define your functions within some larger object. This will prevent naming collisions and keep things very very tidy.

Lets say I want to call my library MyLibrary and I want to organize code within the library into two areas: Area1 and Area2. First thing we want to do is to create the root object.

if (typeof(MyLibrary) == 'undefined')
   MyLibrary = {};

Here we’re just checking that MyLibrary is not already defined. If its not, we’ll create the new object so we can attach more things to it.

After that, its just a matter of using a javascript closure to attach more objects/functions to the root object

(function(ml){

    s.Area1 = (function(){
	return {
		publicFunc : function(){
			console.log('Area 1 public function');
		}
	};
    })();

    s.Area2 = (function(){
	return {
		publicFunc : function(){
			console.log('Area 2 public function');
		}
	};
    })();

})(MyLibrary);

Now in my code, I can call MyLibrary.Area1.publicFunc(); and MyLibrary.Area2.publicFunc(); I can add as many areas to MyLibrary as I please.

As long as I include the undefined check at the top of my files, I can split MyLibrary up into as many files as I like which can give me added flexibility to only apply functionality to certain pages.

April 30, 2012

jQuery Plugin Template

I wanted to share a jQuery plugin template that I use. There are a lot of templates out there but I found this one fairly straight forward to use and provided all the necessary functionality.

What I really needed was a plugin that would provide some helper functions on it. I’ve seen a lot of plugins that did something to the html and attached events but I rarely found any that had public functions done in a way that made sense to me. After doing some Googling, I found something I liked and tweaked it a bit.

(function($){

    var methods = {

        init: function(options){
            return this.each(function() {
               //init each element here
            });
        },

        sampleFunction : function(){

        }

    };

    $.fn.pluginName = function(method){

        if(methods[method]) {
          return methods[method].apply(this,
                        Array.prototype.slice.call(arguments, 1));
        }
        else if(typeof method === 'object' || !method) {
          return methods.init.apply(this, arguments);
        }
        else {
          $.error("Method " +  method + " does not exist");
        }

    }

})(jQuery);

Thats it! It’ll let me do things like this:

$('div').pluginName(); //init code
$('div').pluginName({foo:'bar'}); //init with options
$('div').pluginName('sampleFunction'); //function
April 24, 2012

MSSQL 2008: Mapping old and new data using a merge statement

I thought I’d share some SQL knowledge I picked up today. I’ve used this before but I figure I should publish it as writing it down helps me retain it and someone else may find it useful.

So, I needed to move some data from one table to another which is pretty straight forward. I also needed to output the id of the newly created record so that I could insert it into another table. This is pretty simple with an output statement. However, I also needed the id from the source table that I was pulling the data from. Basically, I needed an old id/new id mapping between the tables.

There are two ways I could go about this. I could change the schema of the target table to have a column to hold the old id and then insert everything in. This seems too intrusive though. There are lots of reasons why this is a bad idea but the best reason is that there is a better way.

The key is a merge statement. If you haven’t familiarized yourself with a merge statement, do yourself a favor and learn it. The syntax can be a little odd at first but its very powerful. All I needed to do was to include the source id in my merge statement and then I can output it in to my mapping. I’ve provided some code below as an example.

First, I declare my mapping table. Pretty straightforward, just a table variable.

declare @map table(
	id_old int not null,
	id_new int not null
)

Next, I do the merge statement.

merge DESTINATION_TABLE as tgt
using (
	select
		old.id,
		old.title,
		old.createdOn
	from SOURCE_TABLE old
) as src(id, title, createdOn)

/* Never match. I only do this because I'm always performing an
* insert. Depending on the requirements of your merge, you can
* change this line to whatever suits you. */
on (1 = 0)

when not matched by target then
	insert (title, createdOn)
		values(src.title, src.createdOn)

output src.id, inserted.id into @map
;

The key to the merge statement is to include the old id in my source block: as src(id, title, createdOn). I’m not required to use the old id in the insert statement but I do have access to it in the output statement. I also have access to all the values that were inserted.

There you have it. A pretty simple way to get a mapping of the old and new ids into one table.