NinjaCipher:-*-:ro60

Archive for the ‘django’ Category

django template wrapper helper

Sunday, March 9th, 2008

edit:
# ericflo pointed out something that I totally forgot about… render_to_string. And he’s completely correct… It does exactly the same thing and most likely does it better… DOH! Well whatever… here is my version anyway ;)

—————————
Here is a handy little helper I cooked up for dynamically loading dynamic content into a reusable template wrapper. It takes the path of a template and a dict of vars to populate, compiles the template and returns the resulting value as a string. You can then pass in the resulting variable into your main context. Pretty simple but very useful.

def wrap_content(template, var_dict):
    from django.template import Context, loader
    c = Context(var_dict)
    t = loader.get_template(template)
    return t.render(c)

called like so

mod = wrap_content('shared/mod_wrapper.html',{'title':'test title','content':'content test',})

django alternate development settings file

Sunday, March 2nd, 2008

So lately I’ve been working out all the kinks of running Django via pydev/eclipse so I can do more dev on my local machine. Since localy I run windows but I deploy onto Ubuntu Linux I’ve come up with a little hack that lets me conditionally load my project settings based on which environment it’s being run in. It’s pretty basic but I find it very helpful. If anyone else has any other approaches pls shout em out.

So all you have to do is create a file with all your development settings in your project folder (same folder the normal settings.py is in) and name it development_settings.py. Besides that you just have to replace the original manage.py in your project with the following manage.py. This one looks to see if your settings.py has DEBUG = True and if so loads the development.py instead.


#!/usr/bin/env python
from django.core.management import execute_manager
try:
    import settings # Assumed to be in the same directory.

    if settings.DEBUG:
        import development_settings
        startup_settings = development_settings
    else:
        startup_settings = settings

except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.nYou'll have to run django-admin.py, passing it your settings module.n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
    execute_manager(startup_settings)

Django find_or_create helpers

Wednesday, February 27th, 2008

OK I’m going to be completely frank. You VERY likely could do this FAR better. But! I looked and have yet to see anything that does this for Django. So, here is my half ass’d attempt at two very helpful methods I picked up from my shady rails past. So by all means call doodoo on my methods and show me your skills because I would love to see someone else’s take on this. Again shouts out to perva.de for being the inspiration for these snippets and thank ifni for Django giving me reason to be excited about a web framework again.

find_or_create

def find_or_create(class_type, params, by='id'):
   if params == None:return None

   try:
      return class_type.objects.get(by+" = "+params[by])
   except class_type.DoesNotExist:
      obj = class_type()
      for column, value in params:
         if hasattr(obj, column):
         _member = getattr(obj,column)
         _member(value)

      obj.save()

      return obj

update_or_create

def update_or_create(class_type, params, by='id'):
   if params == None:return None

   try:
      obj = class_type.objects.get(by+" = "+params[by])
   except class_type.DoesNotExist:
      obj = class_type()

   for column, value in params:
      if hasattr(obj, column):
         _member = getattr(obj,column)
         _member(value)

         obj.save()

         return obj

called like so:

update_or_create(MyModel, request.POST, 'id')
find_or_create(MyModel, request.POST, 'id')

Django Render To Response Hack

Saturday, December 29th, 2007

I was working on perva.de and I needed to add a cookie to the response. Now thats not really a tough thing to do but it has one unfortunate side effect. Basically it makes you have to use the long handed method for rendering the template instead of being able to use the more concise render_to_response shortcut. Reason being that the render_to_response shortcut creates a HttpResponse object for you and when you create a cookie you already have a HttpResponse object thats holding your cookie. So I wrote this simple function that lets you pass in your own pre initialized HttpResponse object instead.

def render_response(*args, **kwargs):
        response = kwargs.pop('response', None)
        if response == None:
            from django.shortcuts import render_to_response
            return render_to_response(*args, **kwargs)
        else:
            from django.template import loader
            response.content = loader.render_to_string(*args, **kwargs)
            return response

You call it the same way as the normal render_to_response except it has an optional param that lets you pass in your pre initialized HttpResponse object.

return render_response('index.html',{'param1': 'param1value'},context_instance=RequestContext(request),response=my_response)

If you pass None as the first param the normal render_to_response is called. The context_instance and the params dict are both optional. You can read about how the normal render_to_response works here.

Now for the disclaimer…

I could be completely missing something simple that already allows you to do this but I didn’t see it. It seems like a very common prob and the folks at the Django project are sick python masters so it wouldn’t surprise me if they already though this through. So if that is the case please leave me a comment and/or call me names and enlighten me to the folly of my ways. I won’t hate you… much ;)

EDIT: I refactored the way the request arg was passed to make it more python like and cleaner. Now you pass it as a kwargs key val pair.