Some Lessons Learnt from Messing with Django and AngularJS

django-logo-negative

square

  1. Key take-away: If you’re thinking of sneaking angular.js as you would any other js file into your ‘static’ folder, you gonna have a bad time. It starts to get really messy when you try to mix and match angular’s url routing mechanism vs. django’s url. The same applies to the templates. I imagine this messiness will always be present if you try to mix a client-side MVC framework with a server-side one.  The best way is to separate angular out from your django project entirely and use the services to communicate with your django application. This means you will need something like django-tastypie or django-rest-framework setup on a separate app. The rest of the points are really more learnings about angular so read on if you’re interested.
  2. You will be confused between the differences of a service and a factory. I’m still confused.
  3. Angular kinda requires you to have a solid understanding of Javascript to be fully effective. You could get away with knowing less Python and still be effective in Django in my opinion.
  4. You can only use one ng-view per view
  5. If your controllers seem to be firing twice, it’s probably because you defined an ng-controller in your html as well as in your route.
  6. If you skipped reading the conceptual overview, it’s a critical document that will help you wrap your head around the angular concepts so don’t.
  7. Angular disables form submissions without an action attribute. If you’re using django-crispy-forms (there’s not reason not to. it’s an excellent form library) to render your form, simply add self.helper.form_action = ‘#’ to fix this.
  8. If you’re wondering why your url end point is getting called twice, its probably because Django is redirecting the url with a trailing slash to a url that does. To fix this, simply escape the backslash like: /custom_api/get_nearest_hotels/:eventId\\/. There is a gotcha to this. It only works in Chrome and Safari. If you’re calling the endpoints via a service factory, Firefox will decide that it’s a good idea to remove the trailing slash from the URL and encode the backslash that was escaping the forward slash to %5C. The result is to use $http. See related angular issue.
  9. Loading templates are a bit of a hassle. There are a few ways to solve this. This guy’s method.
  10. Tricks and tips
    1. http://gpiot.com/angularjs-useful-tips-to-get-started/
    2. http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
  11. Angular and SEO
  12. Get the correct angular folder structure from angular seed
  13. Check out angular-ui
  14. AngularJS in 60 mins
  15. If you see your page flash with angular template tags and then reload again to show the actual content, you need to apply ng-cloak.
  16. $scope.$watch will fire on page load to initialize the watcher.
  17. Always have a ‘.’ in your models. e.g ng-model=user.name and not ng-model=username
  18. $scope.$apply is essentially the way you get the rest of your javascript to sync with angular’s javascript.
  19. Controllers should not contain presentation logic — that belongs in Directives. Controllers strictly should be used for business logic.
  20. If you’re using a moment.js (awesome library) for datetime manipulation, don’t forget that the angular format filters only operate on javascript date objects. So you’ll have to append a .toDate() to cast your moment object into a javascript date.
Advertisements

event_bindings error in Chrome console

If you have an error for event_bindings in your chrome console that looks something like this:

Error in event handler for ‘undefined’:

Unexpected token u SyntaxError: Unexpected token u at Object.parse (native) at chrome-extension://hobijieodegdbpakkfiopclcljnomfnj/ylc.js:120:23 at miscellaneous_bindings:288:9 at chrome.Event.dispatchToListener (event_bindings:390:21) at chrome.Event.dispatch_ (event_bindings:376:27) at chrome.Event.dispatch (event_bindings:396:17) at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:254:22)

 

It is most likely due to a rogue chrome plugin. In manage extensions, search for the one listed in the error message. In my case, it is hobijieodegdbpakkfiopclcljnomfnj and disable it. Restart your browser and all should be well again.

 

Shell Plus, iPython or Shell Prompt Looks Screwed Up

If your prompt ever looks like this:

Python 2.7.3 (default, Oct 22 2012, 06:12:32)
Type "copyright", "credits" or "license" for more information.

IPython 0.13 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
[0;34mIn [[1;34m1[0;34m]: [0m

To fix, simply run: easy_install -a readline

Django Crispy Forms Add HTML5 Data Attributes to Button

Add HTML5 data attributes directly to the button like this:

self.helper.layout = Layout(
                'first_name',
                'last_name',
                'email',
                FormActions(
                    Submit('add', 'Add', css_class="btn-primary"),
                    Button('cancel', 'Cancel', css_class="btn-danger",
                        data_dismiss="modal", aria_hidden="true"),
                    css_class="form-actions form-custom"
                )
            )

instead of this:

HTML('<input type="button" name="cancel" value="Cancel" \
                            id="button-id-cancel" \
                 data-dismiss="modal" aria-hidden="true">'),

13 SEO Tips for Django

This is mostly an on-site specific guide
  1. Use the redirects app to manage url changes Django documentation
  2. Use post save signals to handle slug/url changes in your models Link
  3. Use sitemap The sitemap framework
  4. Use slugfield Model field reference
  5. Use cached template loaders to reduce page load times The Django template language: For Python programmers
  6. Use a css/js compressor to reduce page load times django_compressor
  7. Use django-robots to manage your robots file django-robots
  8. If you’re rolling an e-commerce site, don’t reinvent the wheel, just go with The Best Django CMS. It’s the best code and seo friendly cms framework for django
  9. Manage object level meta data with django-seo
  10. Not django specific but submit your site to google webmasters Webmasters – Google. For bing: Bing – Webmaster Tools
  11. Not django specific again but load your page using Make the Web Faster and make all the recommended changes
  12. Crawl your site content to find broken links using Xenu or Integrity for Mac
  13. To generate image sitemaps, use Django Image Sitemaps

Other Stuff

Mac Trash Hanging on Delete

If you try to clear your trash and it progress bar seems to hang, it’s probably due to a locked file. A few recommendations on the internet requires the user to mess around in terminal and creating a new .Trash2 folder in your home folder and than doing a mv and then delete again.

There’s an easier way to accomplish this. Simply go to your Trash, hit cmd-a, move all the files out into a temporary folder. The remaining ones in Trash will be the locked files.

To unlock, simply right click, Get Info, there should be a small lock on the bottom right of the pop up. Click on it to unlock the file. You should be able to delete it now.

The Tension Between Knowing You’re Good and Getting Paid For It

Dan Pink talks about autonomy, mastery and purpose as the major tenets as to what keeps us motivated (TED Video). He also goes on to say that you need to be compensated enough to take the issue of money off the table.

I find that with developer entrepreneurs chasing startups and small businesses, there is plenty of autonomy, master and purpose in all of our endeavors. We are doing something we genuinely enjoy. There is no TGIF or 3 more hours till knockoff mentality — it’s not really work anymore when you’re deriving pleasure from your work.

However, sometimes there exists a chasm which makes us second guess if what we’re doing is right. That is, we know we are good, we know what we are capable of and where we stand but we’re not getting paid enough to take the issue of money off the table. This is particularly true for someone working in startup that still hasn’t found their product market fit after a period of time.

Perhaps sometimes you find yourself thinking: Mr. XYZ just exited his company for $XM. Is he really any better than me? Is there any tactically knowledge that he possesses that could have made the difference? How far off am I from getting on his level. I call this the ‘Just before getting you get famous moment’.

It kinda becomes a bit of a numbers game — one of your endeavors will eventually reach some level of success (subjective word). You  just gotta keep at it. In the meantime, do whatever service/consultancy gig to put the food on the table. Don’t give up, you’re almost there.