24 February, 2008

Quick Django Tip: Dynamic Application Object Retrieval

In my recent django adventures I needed to introduce site-wide search functionality and in the process of doing so, encountered a small roadblock towards doing so.  Apparently due to the nature of Django's API for db interaction (as of the last stable release version), there is a limitation as to the use of python variables in API calls.  I found this to be a hinderance, but only for so long.  

The follow code snippet was something I whipped together which by utilising Python's 'eval' built-in, overcame the aforementioned limitation regarding the API's ability to interpolate native Python (e.g. non-django explicit) varaibles.

Things to know to understand the following example:  

 search_input is a list of cleaned and pre-processed user-driven terms, split into separate expressions, (e.g. ["dynamic langauge", "agile", "programming", "paradigm"]). 

 search_schema is a dictionary in which the key is the django model/class through whose objects we are attempting to search, and the value is a list of specific model attributes to attempt said search.  (e.g.   User_Profile : ['firstname' , 'lastname', 'address_1', 'bio_info', 'favourite_books'])

container_xref is a simple alias mapping for the actual django application names to our internal references inside this search code base.  Obviously this whole bit could be written without said setup, but for readability given the scope of the actual application involved, and the fact that I was not searching simply a few static fields in one django application, but several dozen fields through about two dozen separate applications, this container_xref dict was appropriate.   It is through this mapping dict which we place any matched object results (so as to not waste any additional space via unnecessary list initialisations.) for eventual results generation.

Note: the key "total_results" in the container_xref was a simple means of keeping track of overall search matches, rather than relying upon the Django templating engine (view) from doing work responsible from the processing (controller) perspective.  In retrospect, there are better ways this could have been handled, and in future point revisions, this will be addressed.

------

for search_string in search_input:
  for application in search_schema.keys():
    for attribute in search_schema[application]:
code_to_eval = "%s.objects.filter( %s__icontains='%s' ).order_by('-id')" %       
                     (str(application), str(attribute), str(search_string))
        try:
          eval_results = eval(code_to_eval)
          for eval_result in eval_results:
            if eval_result not in container_xref[application]:
              container_xref[application].append(eval_result)
              container_xref['total_results'] += 1
        except Exception:
    ### Case specific exception handler types, assignments and resultant actions 
          ### specific to each application in which the above is implemented, go here.

-----

As can be seen from the above, simple inline substitution proceeded by evaluation of said string results in post-compilation dynamic search functionalities within django, addressing simple problems one might run into with the existing API which will most likely be addressed in future versions.  

Your results may vary.

Eric

Labels: , , , ,

04 January, 2008

The New Django Powered Inked Magazine Website is Up!

This will be rather brief as it is more of an announcement than one of my more traditional journal entries. 

After a  short two or so months from start to finish, I have successfully setup my first Django powered website.  Inked Magazine has been relaunched effective January 2nd, 2008.  This replaces the Joomla powered site which existed prior to both myself and the current ownership of the magazine were involved in the project.  

Phase one has been completed, with extras.  The customer photo galleries, the cover photo application, the user profile system as well as the main magazine feature areas have been established and are active.  As of today, I will have available for all registered users the ability to host a blog on our site (using our software which I wrote in a few days), mind you it is still early in the feature process, though it without doubt serves most blog authors needs.  

I will be adding features as time progresses, but until mid-January 2008, I'm on a tight schedule to build the entire forum application so that the beginning of the "New and Improved" Inked Network can go live.  

I don't think one needs Ruby on Rails when you have Django.  Much of the same great functionality and without having to use Ruby all the while using Python.  [Update: After having revisited Ruby as a language on its own, sans Rails notoriety, I've found that my previous assertions regarding Rails specifically was unwarranted.  It simply took my experiences with Django and Python to make Ruby and Rails far clearer to me.]

I will return to my normal posting after the Forum application is up and running.  

Till then, keep on coding.

Labels: , , , , , ,

26 November, 2007

Django and Gant Charts

It has now been almost a full week since I started the complete inkedmag.com site and infrastructure redesign in Python using the Django web publishing framework on FreeBSD, and I am happy to report that it is awesome.   Mind you we're talking version .96 of the product, yet it truly is a dream with which to work.
I only recently started working with (and writing about) Cheetah, a wonderful python template engine, and had to very quickly learn yet another (Django's own template system).  I must admit that Cheetah is easier to ready and learn quickly, but Django's system is considerably more agile in terms of conditionals and modifiers inside the template itself.  There even happens to be a simple mechanism for cycling through a list continually changing on each iteration of the loop within which the cycle conditional resides.  Simply put, it is wonderful for automatically changing the background colour of a row in a list.  
For those unfamiliar with Django, it is simply one of the better web frameworks for content publishing on the web these days.  While learning curve can be a little steep for some pieces of the framework, as a whole the speed at which once can produce working pages and applications is staggering.  The ease and elegance of the system truly makes one enjoying creating new applications within the framework.  
The first application I chose to migrate from native python into the framework was a simple store locator.  The new version not only is considerably less lines of code, the database management was done for me at application creation/initialisation.  I then simply exported the data from my existing application and imported it into the new table(s) Django created.  
I could go on waxing poetic about every little bell and whistle, but I'd just be paraphrasing what many others have already pointed out online and otherwise.  Don't think of it as Ruby on Rails because it isn't, though that isn't to be taken as an insult to Ruby.  It is much more focused, cleaner and far simpler to setup and get running, including all of its own admin interfaces for the applications you create, as well as its own standalone development web server.  Check it out, you won't be disappointed.  This is going to save me a considerable amount of time.
Which brings me to my second point; Gant charts.  They are simply not something I find myself utilising on any regular basis, though I think that is going to change.  I'm my own boss and have found that gant charts produce the easiest visual way to show people the various pieces necessary for a project, when each portion can be expected to start and finish, all in parallel with the other projects for which I'm responsible (and/or coordinating).  

I feel that the use of this tool more than others really gives a great method by which to see which projects will take the bulk of the time, and what projects overlap, etc.  We have a system rewrite to produce and a whole server to replace, not to mention migrating certain custom software into the framework all before the new year.  This is doable, but only because we've clearly set realistic (though tight nonetheless) goals and time frames.    Consider using a gant chart if you have more than one project or component of a project which needs to be done in a given time frame.  Use one if you need to share with one or more people your schedule and need them to understand as quickly and clearly as possible that with which you are juggling or dealing.  You find yourself quickly addicted to its usability.

Labels: , , , , , , , , , , ,