diff --git a/django-docs/build.py b/django-docs/build.py new file mode 100755 index 0000000000..29b5c5add4 --- /dev/null +++ b/django-docs/build.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +""" +Script to build the documentation for Django from ReST -> HTML. +""" + +import os +import sys +import glob +import locale +from docutils.core import publish_parts +from docutils.writers import html4css1 + +SETTINGS = { + 'initial_header_level': 2 +} + +locale.setlocale(locale.LC_ALL, '') + +def build(dirs): + writer = html4css1.Writer() + writer.translator_class = DjangoHTMLTranslator + for dir in dirs: + for fname in glob.glob1(dir, "*.txt"): + in_file = os.path.join(dir, fname) + out_file = os.path.join(dir, os.path.splitext(fname)[0] + ".html") + print "+++", in_file + parts = publish_parts( + open(in_file).read(), + source_path=in_file, + destination_path=out_file, + writer=writer, + settings_overrides={ + 'initial_header_level' : 2, + } + ) + open(out_file, 'w').write(parts['html_body']) + +class DjangoHTMLTranslator(html4css1.HTMLTranslator): + """Remove the damn border=1 from the standard HTML writer""" + def visit_table(self, node): + self.body.append(self.starttag(node, 'table', CLASS='docutils')) + +if __name__ == "__main__": + if len(sys.argv) > 1: + build(sys.argv[1:]) + else: + build([os.getcwd()]) diff --git a/django-docs/db-api.txt b/django-docs/db-api.txt new file mode 100644 index 0000000000..aebfd36cfa --- /dev/null +++ b/django-docs/db-api.txt @@ -0,0 +1,258 @@ +====================== +Database API reference +====================== + +XXX INTRO HERE XXX + +Throughout this reference, I'll be referring to the following Poll application:: + + class Poll(meta.Model): + module_name = 'polls' + verbose_name = 'poll' + db_table = 'polls' + fields = ( + meta.SlugField('slug', 'slug', unique_for_month='pub_date'), + meta.CharField('question', 'question', maxlength=255), + meta.DateTimeField('pub_date', 'date published'), + meta.DateTimeField('expire_date', 'expiration date'), + ) + + class Choice(meta.Model): + module_name = 'choices' + verbose_name = 'choice' + db_table = 'poll_choices' + fields = ( + meta.IntegerField('poll_id', 'poll', rel=meta.ManyToOne(Poll, 'poll', 'id', + edit_inline=True, edit_inline_type=meta.TABULAR, num_in_admin=10, + min_num_in_admin=5)), + meta.CharField('choice', 'choice', maxlength=255, core=True), + meta.IntegerField('votes', 'votes', editable=False, default=0), + ) + +Basic lookup functions +====================== + +Each model exposes three basic functions for lookups: ``get_object``, +``get_list``, and ``get_count``. These functions all take the same arguments, +but ``get_object`` assumes that only a single record will be returned (and +raises an exception if that's not true), ``get_count`` simple returns a count of +objects matched by the lookup, and ``get_list`` returns the entire list. + +Field lookups +============= + +Basic field lookups take the form ``field__lookuptype`` (that's a +double-underscore). For example:: + + polls.get_list(pub_date__lte=datetime.datetime.now()) + +translates (roughly) into the following SQL: + + SELECT * FROM polls WHERE pub_date < NOW(); + +The DB API supports the following lookup types: + + ========== ============================================================== + Type Description + ========== ============================================================== + exact Exact match: ``polls.get_object(id__exact=14)`` + iexact Case-insensitive exact match: + ``polls.get_list(slug__iexact="foo")`` matches a slug of ``foo``, + ``FOO``, ``fOo``, etc. + contains Case-sensitive contains test: + ``polls.get_list(question__contains="spam")`` returns all polls + that contain "spam" in the question. + icontains Case-insensitive contains + gt Greater than: ``polls.get_list(id__gt=4)`` + gte Greater than or equal to + lt Less than + lte Less than or equal to + startswith Case-sensitive starts-with: + ``polls.get_list(question_startswith="Would")`` + endswith Case-sensitive ends-with + range Range test: + ``polls.get_list(pub_date__range=(start_date, end_date)`` + returns all polls with a pub_date between ``start_date`` + and ``end_date`` (inclusive). + year For date/datetime fields, exact year match: + ``polls.get_count(pub_date__year=2005)``. + month For date/datetime fields, exact month match. + day For date/datetime fields, exact day match. + isnull True/False; does is IF NULL/IF NOT NULL lookup: + ``polls.get_list(expire_date__isnull=True)``. + ========== ============================================================== + +Multiple lookups are of course allowed, and are translated as "ands":: + + polls.get_list( + pub_date__year=2005, + pub_date__month=1, + question__startswith="Would", + ) + +retrieves all polls published in Jan. 2005 whose question starts with "Would." + +"Or" lookups are also possible:: + + XXX FIXME XXX + +Ordering +======== + +The results are automatically ordered by the ordering tuple given by the +``ordering`` key in the model, but the ordering may be explicitly +provided by the ``order_by`` argument to a lookup:: + + polls.get_list( + pub_date__year=2005, + pub_date__month=1, + order_by=(("pub_date", "DESC"), ("question", "ASC")), + ) + +The result set above will be ordered by ``pub_date`` (descending), then +by ``question`` (ascending). Just like in models, the ``order_by`` clause +is a list of ordering tuples where the first element is the field and the +second is "ASC" or "DESC" to order ascending or descending. You may also +use the tuple ``(None, "RANDOM")`` to order the result set randomly. + +Relationships (joins) +===================== + +Joins may implicitly be performed by following relationships: +``choices.get_list(poll__slug__exact="eggs")`` fetches a list of ``Choice`` +objects where the associated ``Poll`` has a slug of ``eggs``. Multiple levels +of joins are allowed. + +Given an instance of an object, related objects can be looked up directly using +connivence functions, for example, if ``poll`` is a ``Poll`` instance, +``poll.get_choice_list()`` will return a list of all associated choices (astute +readers will note that this is the same as +``choices.get_list(poll_id__exact=poll.id)``, except clearer). + +Each type of relationship creates a set of methods on each object in the +relationship. These created methods go both ways, so objects that are +"related-to" need not explicitly define reverse relationships; that happens +automatically. + +One-to-one relations +-------------------- + +Each object in a one-to-one relationship will have a ``get_relatedobject()`` +method. For example:: + + class Place(meta.Model): + ... + fields = ( + ... + ) + + class Restaurant(meta.Model): + ... + fields = ( + meta.IntegerField('id', 'ID', primary_key=True, + rel=meta.OneToOne(places.Place, 'place', 'id')), + ... + ) + +In the above example, each ``Place`` will have a ``get_restaurant()`` method, +and each ``Restaurant`` will have a ``get_place()`` method. + +Many-to-one relations +--------------------- + +In each many-to-one relationship the related object will have a +``get_relatedobject()`` method, and the related-to object will have +``get_relatedobject()``, ``get_relatedobject_list()``, and +``get_relatedobject_count()`` methods (the same as the module-level +``get_object()``, ``get_list()``, and ``get_count()`` methods). + +Thus, for the ``Poll`` example at the top, ``Choice`` objects will have a +``get_poll()`` method, and ``Poll`` objects will have ``get_choice()``, +``get_choice_list()``, and ``get_choice_count()`` functions. + +Many-to-many relations +---------------------- + +Many-to-many relations result in the same set of methods as `Many-to-one relations`_, +except that the ``get_relatedobjects()`` function on the related object will +return a list of instances instead of a single instance. So, if the relationship +between ``Poll`` and ``Choice`` was many-to-many, ``choice.get_polls()`` would +return a list. + +Relationships across applications +--------------------------------- + +If a relation spans applications -- if ``Place`` was had a ManyToOne relation to +a ``geo.City`` object, for example -- the name of the other application will be +added to the method, i.e. ``place.get_geo_city()`` and +``city.get_places_place_list()``. + +Selecting related objects +------------------------- + +Relations are the bread and butter of databases, so there's an option to "follow" +all relationships and pre-fill them in a simple cache so that later calls to +objects with a one-to-many relationship don't have to hit the database. If you pass +``select_related=True`` to a lookup, this pre-caching of relationships will be performed. +This results in (sometimes much) larger queries, but it means that later use of +relationships is much faster. + +For example, using the Poll and Choice models from above, if you do the following:: + + c = choices.get_object(id__exact=5, select_related=True) + +Then subsequent calls to ``c.get_poll()`` won't hit the database. + +Limiting selected rows +====================== + +The ``limit``, ``offset``, and ``distinct`` keywords can be used to control +which rows are returned. Both ``limit`` and ``offset`` should be integers which +will be directly passed to the SQL ``LIMIT``/``OFFSET`` commands. + +If ``distinct`` is True, only distinct rows will be returned (this is equivalent +to a ``SELECT DISTINCT`` SQL clause). + +Other lookup options +==================== + +There are a few other ways of more directly controlling the generated SQL +for the lookup. Note that by definition these extra lookups may not be +portable to different database engines (since you're explicitly writing +SQL code) and should be avoided where ever possible.: + +``params`` +---------- + +All the extra-SQL params described below may use standard Python string +formatting codes to indicate parameters that the database engine will +automatically quote. The ``params`` argument can contain any extra +parameters to be substituted. + +``select`` +---------- + +The ``select`` keyword allows you to select extra fields. This should be a +dict mapping field names to a SQL clause to use for that field. For example:: + + polls.get_list( + select={ + 'choice_count' : 'SELECT COUNT(*) FROM choices WHERE poll_id = polls.id' + } + ) + +Each of the resulting ``Poll`` objects will have an extra ``choice_count`` with +a count of associated ``Choice`` objects. Note that the parenthesis required by +most database engines around sub-selects are not required in Django's ``select`` +clauses. + +``where`` / ``tables`` +---------------------- + +If you need to explicitly pass extra ``WHERE`` clauses -- perhaps to perform +non-explicit joins -- use the ``where`` keyword.. If you need to +join other tables into your query, you can pass their names to ``tables``. + +Creating new objects +==================== + diff --git a/django-docs/images/flatfiles_admin.png b/django-docs/images/flatfiles_admin.png new file mode 100644 index 0000000000..391a629348 Binary files /dev/null and b/django-docs/images/flatfiles_admin.png differ diff --git a/django-docs/images/users_changelist.png b/django-docs/images/users_changelist.png new file mode 100644 index 0000000000..d5f9c016cc Binary files /dev/null and b/django-docs/images/users_changelist.png differ diff --git a/django-docs/model-api.txt b/django-docs/model-api.txt new file mode 100644 index 0000000000..b794da2678 --- /dev/null +++ b/django-docs/model-api.txt @@ -0,0 +1,760 @@ +=============== +Model reference +=============== + +XXX INTRO XXX + +Options for models +================== + +A list of all possible options for a model object follows. Although there's a wide +array of possible options, only ``fields`` is required. + +``admin`` +--------- + +A ``meta.Admin`` object; see `Admin options`_. If this field isn't given, +the object will not have an admin interface. + +``db_table`` +------------ + +The name of the database table to use for the module:: + + db_table = "pizza_orders" + +If not given, this will use ``app_label + '_' + module_name``. + +``exceptions`` +-------------- + +Names of extra exception subclasses to include in the generated module. +These exceptions are available from instance methods and from module-level +methods:: + + exceptions = ("DisgustingToppingsException", "BurntCrust") + +``fields`` +---------- + +A list of field objects; see `Field objects`_. For example:: + + fields = ( + meta.CharField('customer_name', 'customer name', maxlength=15), + meta.BooleanField('use_extra_cheese', 'use extra cheese'), + meta.IntegerField('customer_type', 'customer type', choices=CUSTOMER_TYPE_CHOICES), + ... + ) + +``get_latest_by`` +----------------- + +The name of a date or datetime field; if given, the module will have a +``get_latest()`` function which fetches the "latest" object in terms of +that field:: + + get_latest_by = "order_date" + +``module_constants`` +-------------------- + +A dict of name/values to use as extra module-level constants:: + + module_constants = { + 'MEAT_TYPE_PEPPERONI' : 1, + 'MEAT_TYPE_SAUSAGE' : 2, + } + +``module_name`` +--------------- + +The name of the module:: + + module_name = "pizza_orders" + +If not given this will use a lowercased version of the class name. + +``order_with_respect_to`` +------------------------- + +Marks this object as "orderable" with respect to the given field. This is +almost always used with related objects to allow them to be ordered with +respect to a parent object. For example, if a ``PizzaToppping`` relates to +a ``Pizza`` object, you might use:: + + order_with_respect_to = 'pizza_id' + +to allow the toppings to be ordered with respect to the associated pizza. + +``ordering`` +------------ + +The default ordering for tho object:: + + ordering = (('order_date', 'DESC'),) + +This is a tuple of 2-tuples; each 2-tuple is ``(field_name, ordering_type)`` +where ordering_type is either ``"ASC"`` or ``"DESC"``. You may also use the +magic ``(None, "RANDOM")`` ordering tuple for random ordering. + +``permissions`` +--------------- + +Extra permissions to enter into the permissions table when creating this +object. A add, delete, and change permission is automatically created for +each object; this option specifies extra permissions:: + + permissions = (("may_delivier_pizzas", "Can deliver pizzas"),) + +This is a list of 2-tuples of +``(permission_code, human_readable_permission_name)``. + +``unique_together`` +------------------- + +Sets of field names that, taken together, must be unique:: + + unique_together = (("driver_id", "restaurant_id"),) + +This is a list of lists of fields that must be unique when considered +together. + +``verbose_name`` +---------------- + +A human-readable name for the object, singular:: + + verbose_name = "pizza" + +If not given, this will use a munged version of the class name: +``CamelCase`` becomes ``camel case``. + +``verbose_name_plural`` +----------------------- + +The plural name for the object:: + + verbose_name_plural = "stories" + +If not given, ``verbose_name + "s"`` will automatically be used. + +Field objects +============= + +The list of fields is the most important part of a data model. Each item in +the ``fields`` list is an instance of a ``meta.Field`` subclass, and maps to +a database field. + +All field objects -- except for ``ForeignKey`` and ``ManyToManyField`` (see +below) -- take two positional arguments and a number of keyword arguments. +The positional arguments are the field name and the human-readable name. The +field name must be a valid Python identifier, but the human-readable name can +contain spaces, punctuation, etc. + +General field options +--------------------- + +Each type of field takes a different set of options, but there are some +options that are common to all field types. These options are: + + ====================== =================================================== + Option Description + ====================== =================================================== + ``blank`` If ``True``, the field is allowed to be blank. + Note that this is different from ``null`` in that + string fields will store the empty string instead of + ``NULL`` internally; this means that to create a + field that stores nulls you must pass ``blank=True`` + and ``null=True`` . + + ``choices`` A list of 2-tuples to use as choices for this + field.If this is given, instead of the standard + field a option menu will be used, limiting choices + to the choices given. A choices list looks like:: + + YEAR_IN_SCHOOL_CHOICES = ( + ('FR', 'Freshman'), + ('SO', 'Sophomore'), + ('JR', 'Junior'), + ('SR', 'Senior'), + ('GR', 'Graduate'), + ) + + The first element in each tuple is the actual value + to be stored; the second element is the human + readable name for the option. + + ``core`` For objects that are edited inline to a related + object (see Relationships_). If all "core" fields + in an inline-edited object are cleared, the + object will be considered to be deleted. + + It is an error to have an inline-editable + relation without at least one core field. + + ``db_index`` If ``True``, the SQL generator will create a database + index on this field. + + ``default`` The default value for the field. + + ``editable`` ``True`` by default, if set to ``False`` the field + will not be editable in the admin. + + ``help_text`` Extra "help" text to be displayed with the field. + + ``null`` If ``True`` empty values in the field will be + stored as ``NULL`` in the database. + + XXX does null imply blank? XXX + + ``primary_key`` If ``True`` this field is the primary key for the + table. You only need to use this if you don't want + the standard "id" field created and used as the + primary key. + + Implies ``blank=False``, ``null=False``, and + ``unique=True``. Only one primary key is allowed + on each object. + + ``radio_admin`` If ``choices`` is given, or if the field is a + ManyToOne relation, use a radio button interface + for the choices instead of the standard options + menu interface. + + ``rel`` The field's relation; see Relationships_. + + ``unique`` If ``True`` this field must be unique throughout + the table. + + ``unique_for_date`` Set this to the name of a ``DateField`` or + ``DateTimeField`` to require that this field + be unique for the value of the date field. That + is, if you have a field, ``title`` that has + ``unique_for_date="pub_date"``, then it is an + error to have two rows with the same ``title`` + and the same ``pub_date``. + + ``unique_for_month`` Like ``unique_for_date``, but requires the field + to be unique with respect to the month. + + ``unique_for_year`` Like ``unique_for_date`` and ``unique_for_month`` + but, well, you get the idea. + + ``validator_list`` A list of extra validators to apply to the field. + See the `Form fields guide`_ for information about + validators. + ====================== =================================================== + +.. _`Form fields guide`: http://www.djangoproject.com/FIXME/ + +Field Types +----------- + +``AutoField`` +````````````` + +An ``IntegerField`` that automatically increments. You usually won't need to +use this directly; a primary key field will automatically be added to your +model if you don't specify otherwise. That automatically added field is:: + + meta.AutoField('id', 'ID', primary_key=True) + +``BooleanField`` +```````````````` + +A true/false field. + +``CharField`` +````````````` + +A text field. These are displayed in the admin as single-line text inputs, so +for large amounts of text use a ``TextField``. + +``CharField``s have an extra required argument: ``maxlength``; the maximum +length (in characters) of the field. + +``CommaSeparatedIntegerField`` +`````````````````````````````` + +A field of integers separated by commas. + +``DateField`` +````````````` + +A, um, date field. Has a few extra optional options: + + ====================== =================================================== + Option Description + ====================== =================================================== + ``auto_now`` Automatically set the field to now every time the + object is saved. Useful for "last-modified" + timestamps. + + ``auto_now_add`` Automatically set the field to now when the object + is first created. Useful for creation timestamps. + ====================== =================================================== + +``DateTimeField`` +````````````````` + +A date and time field. Takes the same extra options as ``DateField``. + + +``EmailField`` +`````````````` + +A ``CharField`` that checks that the value is a valid email address. Because +validating email addresses can be tricky, this is a pretty loose test. + +``FileField`` +````````````` + +A file-upload field. Takes on additional option, ``upload_to`` which is +a path to upload the file to. This path may contain `strftime formatting`_ +which will be replaced by the date/time of the file upload (so that uploaded +files don't fill up the given directory). + +.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 + +``FloatField`` +`````````````` + +A floating-point number. Has two additional required options: + + ====================== =================================================== + Option Description + ====================== =================================================== + ``max_digits`` The maximum number of digits allowed in the number. + + ``decimal_places`` The number of decimal places to store with the + number + ====================== =================================================== + +For example, to store numbers up to 999 with a resolution of 2 decimal places, +you'd use:: + + meta.FloatField(..., max_digits=5, decimal_places=2) + +And to store numbers up to one million with a resolution of 10 decimal places:: + + meta.FloatField(..., max_digits=19, decimal_places=10) + +``ForeignKey`` +`````````````` + +A many-to-one relationship to the primary key in another object. So, to give a +``Topping`` object a many-to-one relationship to ``Pizza`` (i.e. there are +many toppings on a pizza):: + + meta.ForeignKey(Pizza) + +This is equivalent to (but much clearer than):: + + meta.IntegerField('pizza_id', 'pizza', rel=meta.ManyToOne(Pizza, 'pizza', 'id')) + +``ForeignKey`` fields take all the arguments of ``ManyToOne`` relations (see +Relationships_, below for what those arguments are), plus the following extra +options: + + ====================== =================================================== + Option Description + ====================== =================================================== + ``to_field`` The field on the related object that the relation + is to. This is almost always ``id``, but if the + PK on the other object is named something + different, this is how to indicate that. + + ``rel_name`` The name of the relation. In the above exmaple, + this would default to 'pizza' (so that the + ``Toppings`` object would have a ``get_pizza()`` + function; if you set ``rel_name`` to "pie", then + the function would be called ``get_pie()`` and the + field name would be ``pie_id``. + ====================== =================================================== + + +``ImageField`` +`````````````` + +Like a ``FieldField``, but validates that the uploaded object is a valid +image. Has two extra optional arguments, ``height_field`` and ``width_field`` +which, if set, will be auto-populated with the height and width of the image. + +``IntegerField`` +```````````````` + +An integer, surprisingly. + +``IPAddressField`` +`````````````````` + +An IP address, in string format (i.e. "24.124.1.30"). + +``ManyToManyField`` +``````````````````` + +XXX document once Adrian reworks this XXX + +``NullBooleanField`` +```````````````````` + +Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this +instead of a ``BooleanField`` with ``null=True`` . + +``PhoneNumberField`` +```````````````````` + +Validates that the value is a valid phone number. + +``PositiveIntegerField`` +```````````````````````` + +Like an ``IntegerField``, but must be positive. + +``PositiveSmallIntegerField`` +````````````````````````````` + +Like a ``PositiveIntegerField``, but only allows values below 32767. + + +``SlugField`` +````````````` + +A "slug" suitable for parts of a URL; only allows alpha-numeric characters and +underscores. + +Implies ``maxlength=50`` and ``db_index=True``. + +Accepts an extra option, ``prepopulate_from`` which is a list of fields from +which to auto-populate the slug. + +``SmallIntegerField`` +````````````````````` + +Like an ``IntegerField``, but must be between -32768 and 32767. + +``TextField`` +````````````` + +A large text field (``