Search This Blog

Tuesday, September 22, 2009

Django, Feel it

Portable:
http://blog.dpeepul.com/2009/08/31/top-10-tips-to-a-new-django-developer/

Think reusable:
make use of reverse(), permalink(), and {% url %} tag.
get data from another model (get_model), and provide a default model
make your form pluggable

a good example is to have a view function, with request as the first argument, then people can specify their own form, template, and url they can go after the view.
http://ericholscher.com/projects/reusable-app-docs/index.html
http://www.youtube.com/watch?v=A-S0tqpPga4

Where should your App live?
A project has a collection of apps(comments, tag, etc...). Try decouple your apps from your site, so you can use your app in another project, and other people can use yours app, too
http://www.muhuk.com/2009/03/django-where-should-my-app-live/


In urls.py:

url is how user can type in the address bar, sending a command or go to a place
i.e. (regular expression, path.to.viewFunction)
then the matching method, can be found in the view (views.py) to run.

You can pass argument in the urls.py, with (), so your view method can get extra argument.
You can use "name grouping" for as keyword argument instead as positional argument

In views.py
in each method, you can load the model (database), play with it. At the end, you can also
"render_to_response" to specify a template to show, and passing some variables into
the template.

views takes an http request (from your urls.py), and (almost always) return an response.
template can help the view. it helps to generate some "text".

If http request and http response are not enough for you, you can always write your own http middleware. So that you can do something in between request and response, without copy&paste code to each of your view, but simply, import your middleway.

In models.py
you can set the database schema here. To let views or admin to use it, just tell them to
import the model class. And then you can use the API to make queries.

model is just "a python class". In your view after retrieving your model, you can add any attribute to it if you want.

Django supports cache framework. Use it if speed is your big priority.

HttpReqest and HttpResponse:
You can set cookie, get cookie, rediret, do all kinds of essential operations.
more on the doc...

User Profile:
In user authentication, we can store profile for each user (built-in feature)
more on the doc...

Modify Model Frequently (during development)
  1. Modify the model
  2. manage.py reset appname
  3. use Fixture to generate test data
  4. goto 1.
more...



Debug your Django
Remeber pdb? the python debugger. Just add import pdb, pdb.set_trace() to your code where you want to stop. You can see information in your terminal!

No comments: