Play nice

The saga of Django-Angular continues!

We finally made a bit of a breakthrough.  I realized that Angular routing can work with Django routing just fine- it just takes a little of massaging both egos.  You see, no one likes to be left out, least of all Django, and that’s where my thinking was falling flat.  I thought we could just have the Angular routes take over, but where would they go?  Django is handling the ‘response’ part of any request in the http chain, so yes- we could set up Angular routes to handle some views, but still had to create those (literally in the file) within Django.

So we added some $routeProvider.when() calls.  Cool trick I also learned- the templateUrl option can receive a function.  So really, we only needed one- pass the function the route params, then grab the current param off that and return it.  This way, we don’t have to set up individual routes for each path- one will do the trick:

when('/:id', {
  templateURL: function(params) {
    return 'path/to/your/file';

This awesome snippet brought to you by this badass:

Note that I’m leaving off the ‘.html’ that might go at the end of the return statement- Django doesn’t like when you tell it what type of file to get, it does that all on its own!  It will still work on another framework (or no framework), just add the ‘.html’ to the end of the string.

The final step was to appease Django.  First in

url(r'path-start-here/(?P[a-zA-Z0-9_-]+^$', viewnamehere)

And finally, in

def viewnamehere(request, endpath=None):
    render(return_to_response('yourfolder/'+endpath+'.html', locals())
  return render_to_response('yourfolder/yourdefaultfile.html', locals())

I’m sure there’s something off here- it works, but only with one folder (if I try to make a 2nd url and view for a different folder, Angular never seems to pick it up).  So there’s more work to do, for sure, but it’s very useful for a project that doesn’t require too much deep organization.  It was also neat to learn a bit more about Django views- I didn’t realize you could pass the optional parameter (endpath=None) and have two outcomes for the same view (though, in retrospect, it does seem quite simple!).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s