Skip to content

Instantly share code, notes, and snippets.

@cube-drone
Last active August 29, 2015 14:03
Show Gist options
  • Save cube-drone/f47db61a8f1a634af463 to your computer and use it in GitHub Desktop.
Save cube-drone/f47db61a8f1a634af463 to your computer and use it in GitHub Desktop.
Django tips for Bill
  1. Because you're on a greenfield project, you have the option to use Python3. Seriously consider it - you lose access to a few old, less-maintained libraries, but you gain infinitely less Unicode woes, which was the big change from python to python3
  2. To parse DAT XML, you're going to want to look at lxml and BeautifulSoup. lxml provides the Proper Parser For XML, and BeautifulSoup sits on top of it and does things like "does its best to guess at how to deal with broken xml" and "provides a pretty, pythonic search interface".
  3. Django comes with so much User Auth out of the box. There's a pre-baked User model that you should use as your core 'user' model. There are pre-built views providing login, registration, and password-reset. Because there's a pre-cooked User model that the system provides for you, and it might not always have all of the fields that you need to attach to a user, a common pattern is to create a "UserPreferences" application, containing just the one UserPreference model, and views to work with it.
  4. The ModelForm will save you lots time if you use it wisely. Just point it at a Model and poof, free Form object.
  5. A CSS and Javascript front-end framework full of useful display tools, like Bootstrap, will save you a lot of time dicking about with UI primitives.
  6. Once you have a form, it's really nice if you can automatically render the form rather than having to hand-code it. django-bootstrap-form will build the Form object into a pretty block of HTML for you: http://django-bootstrap-form.readthedocs.org/en/latest/
  7. Use "editable=False" on Model fields that you don't want to show up in forms.
  8. When you're asking yourself, 'where should I put this code', the order goes like this: Models, Forms, Views, Templates, Template-Tags. As much as possible, keep your logic in your models. You can load a lot of things into those model fields - validators ("This should be all lower-case"), logging, pre-save and post-save steps (by overriding the 'save' class), user-friendly field descriptions, lots of things - because everything flows from your Models. Views should, ideally, be pretty sparse - more about fetching collections of Models and Forms and displaying them, less about business logic (which should be in the model). Templates should be almost free of logic - there's a reason why Django provides so few programming primitives in their templates. Template-tags... are a bad place to put serious logic, they're for UI-stuff and only UI-stuff.
  9. A lot of people think that Class-Based Views are a mistake. I tend to agree with them. Stick with Function-Based Views. http://lukeplant.me.uk/blog/posts/djangos-cbvs-were-a-mistake/
  10. Use PostgreSQL, not MySQL. Django has first-class Postgres support, and it's a better database.
  11. You can get a lot of performance gains out of 'select_related', 'prefetch_related', and 'db_index'. Turn to these before you look to more heavyweight solutions.
  12. If you're planning on searching through a literal mountain of data, consider enlisting Django-Haystack and then ElasticSearch or Solr. These are great big heavyweight search tools, with a lot of setup and management time, so its best to wait to look in to this until it has been proven that database-provided searching (which is pretty fast, especially if you're properly indexing fields) is not fast enough for your purposes.
  13. Try to silo your apps into separate logical units. The right number of models in an app is "zero to five". "UserPreferences", for example, can logically be an app all to itself. Keep views, templates, urls, and static files in their own apps. You can still have templates and files and urls common to the whole application in the outermost layer of the app (or in a 'core' app). If you're building common functionality, consider keeping it in its own app. An app doesn't need models and views - it can also just be a logical group of useful things.
  14. There's a great book, called "Two Scoops of Django", that basically just covers best practices for Django. It's short, and a little spendy, but if you load it on a portable device and take it to a park, it's a good read - although it's best for people who have a little bit of experience with Django already.
  15. Use pip. (Well, pip3 for python3) Include a file containing your pip deps.
  16. Read pep8.

Let's talk a bit about the FIVE-AND-A-HALF ESSENTIAL LIBRARIES EVERY DJANGO PROJECT NEEDS. (Buzzfeed title free of charge.)

  1. south - If you're working with a live database, the ability to keep track of "the current version of the database schema" is crazy mega-useful. In popular frameworks like Ruby on Rails or Scala's Play, 'migrations' are baked right in to the framework - they're called "evolutions" in Play, but just because that's a much cooler name. The concept of a migration is simple - When you deploy your application for the very first time, you create Migration 0, which contains a description of your database schema at that moment. Then, any time anybody changes the database schema during ongoing project development, they produce a new migration, which contains instructions for non-destructively altering the database schema to bring it up to date with the new schema. (Migration 1 - Added "Spin" Field) (Migration 2 - Removed "Spin" Field, That Was a Bad Idea) Unfortunately, Django didn't build this in to the framework from the get-go, so some enterprising third party developers added it as a plugin called 'south' and it's been a gold standard ever since... until Django 1.7, which should launch later this year, where they've rolled south right into the Django core libraries.
  2. pytz - Django comes with intelligent time-zone support turned off. Then, in the documentation, they say "always, always turn this on, unless you sincerely want to experience Leap-Year and Daylight Savings woes". https://docs.djangoproject.com/en/dev/topics/i18n/timezones/
  3. django-autoslug - Use slugs everywhere. Any time you have a url like yoursite.com/employees/182 in your project, a tiny kitten is thrown against a wall. For just about every database object, there are one or more fields that form a better description of the object than just its database ID, and you can make this description into a unique URL - so, instead of yoursite.com/employees/182, yoursite.com/employees/steve-smith2. Throughout your application code, you can treat this slug like an ID - use it to fetch your object, pass it around in URLS, and the like.
  4. django-jsonfield - This thing is like a swiss-army knife of usefulness. Do you have strange data in your application that's hard to fit into standard database fields - in your case, like, a Matrix of data? JSONField has your back. In our work application, we've developed a habit of attaching a "config" JSONField to just about any Model we create, because it's a great way to give ourselves a Mongo-like flexibility in our app- if we want to add a quick and dirty field to any of our models in production without having to run a migration, JSONField has our back. I'm running a one-time import task and I want to add config['importname'] = "The Spring 2014 Import", config['importdate'] = datetime.datetime.now() - I can, and then later on, when the one-time import task goes horribly wrong I can reverse it by deleting any record I find with "The Spring 2014 Import" in its config data.
  5. BeautifulSoup - I already mentioned this one - it's a toolkit for parsing XML. And HTML. And eating wierd parse errors, and giving you a parse tree anyways, dammit, because it BELIEVES in itself.
  6. Bootstrap or Foundation - Bring a UI library full of pre-baked layout primitives to the party. Save yourself time fiddling with CSS. Don't bother fiddling with the build processes or default styles for either of these if you're building software that only your institution will see - it's mostly just bikeshed painting.

Also I have MANY MORE OPINIONS so feel free to ask me as you go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment