Вы находитесь на странице: 1из 2

Model elds

Common model eld options null blank choices db_column db_index db_tablespace default error_messages help_text primary_key unique unique_for_date unique_for_month verbose_name validators = False = False = [(1, Choice 1), ] = column_name = False = tablespace_name = value_or_callable = {name: Message, }, = long help text = False = False = date_eld = month_eld = Field Name = [validator_obj, ] Model Meta options abstract app_label db_table db_tablespace get_latest_by index_together managed order_with_respect_to ordering permissions proxy unique_together verbose_name verbose_name_plural = False = "applabel" = "table_name" = "space_name" = "eld_name" = [("eld1", "eld2"), ] = False = "eld" = ["eld_name", ] = [("code", "text label"), ] = False = [("eld1", "eld2"), ] = "verbose name" = "plural verbose names"

Grove.io
Enterprise chat, backed by IRC, built by Revsys. http://grove.io/ QuerySet methods all() annotate(**annotations) dates(eld, "year/month/day", "ASC/DESC") defer(*elds) distinct(*elds) (1.4) exclude(**lookups) lter(**lookups) none() only(*elds) order_by(*elds) prefetch_related(eld1, eld2, ) raw(sql, params) reverse() select_for_update(nowait=False) select_related(eld, eld2, , depth=1) using(db_alias) values(*elds) values_list(*elds) values_list(eld, at=True) aggregate(**aggregations) bulk_create(list_of_objects) count() create(**attributes) delete() exists() get(**lookups) get_or_create(**attributes, defaults={}) in_bulk(id_list) iterator() latest(eld) update(**attributes) Lookups exact, iexact contains, icontains startswith, endswith, istartswith, iendswith in gt, lt, gte, lte range year, month, day isnull regex, iregex = string = string = string = list / queryset = date / int / oat / decimal = (lower, upper) = int = bool = r^reg\. exp\.

ModelAdmin options & callbacks actions = ["method", callback, ] actions_on_bottom = False actions_on_top = True actions_selection_counter = True add_form_template = 'add_form.html' change_form_template = 'change_form.html' change_list_template = 'changelist.html', date_hierarchy = "date_eld" delete_conrmation_template = 'delete.html' delete_selected_conrmation_template = 'del.html' exclude = ["eld_name", ] elds = ["eld_name", ] eldsets = [("Name", {"elds": ["eld_name", ]}), ] lter_horizontal = ["m2m_eld", ] lter_vertical = ["m2m_eld", ] form = ModelFormClass formeld_overrides = {TextField: {"widget": MyWidget}, } inlines = [InlineClass, ] list_display = ["eldname", callable, ] list_display_links = ['eld_name', ] list_editable = ['eld_name', ] list_lter = ['eld_name', ] list_max_show_all = 200 list_per_page = 100 list_select_related = False object_history_template = 'admin/history.html', ordering = ['eld_name'] paginator = Paginator prepopulated_elds = {'slug': ['title'], } radio_elds = {'fk_eld': admin.HORIZONTAL, } raw_id_elds = ['fk_or_m2m_eld', ] readonly_elds = ['eld_name', ] save_as = False save_on_top = False search_elds = ['eld_name'] add_view(self, request, form_url='', extra_context={}) changelist_view(self, request, extra_context={}) change_view(self, request, object_id, extra_context={}) delete_model(self, request, obj) delete_view(self, request, object_id, extra_context={}) formeld_for_choice_eld(self, db_eld, request, **kw) formeld_for_foreignkey(self, db_eld, request, **kw) formeld_for_manytomany(self, db_eld, request, **kw) get_list_display(self, request) get_list_display_link(self, request, list_display) get_ordering(self, request) get_paginator(self, queryset, per_page, orphans=0, allow_empty_rst_page=True) get_prepopulated_elds(self, request, obj=None) get_readonly_elds(self, request, obj=None) get_urls(self) has_add_permission(self, request) has_change_permission(self, request, obj=None) has_delete_permission(self, request, obj=None) history_view(self, request, object_id, extra_context={}) message_user(self, request, message) queryset(self, request) save_formset(self, request, form, formset, change) save_model(self, request, obj, form, change) save_related(self, request, obj=None)

We know Django. http://revsys.com/

AutoField BigIntegerField BooleanField, NullBooleanField CharField max_length CommaSeparatedIntegerField max_length DateField, DateTimeField DecimalField max_digits decimal_places EmailField max_length FileField upload_to storage max_length FilePathField path match recursive max_length FloatField FileField upload_to storage max_length ImageField upload_to storage height_eld width_eld max_length IPAddressField GenericIPAddressField protocol unpack_ipv4 SlugField max_length SmallIntegerField TextField TimeField URLField Model relationships ForeignKey(OtherModel) related_name limit_choices_to to_eld on_delete ManyToManyField(OtherModel) related_name limit_choices_to to_eld symmetrical through db_table OneToOneField(OtherModel) parent_link related_name limit_choices_to to_eld on_delete = things = Q(foo=bar, ...) = key_eld_name = (see right) = things = Q(foo=bar, ...) = key_eld_name = True, = RelationshipModel = table_name = False = thing = Q(foo=bar, ...) = key_eld_name = (see right) = both | IPv4 | IPv6 = False = 100 = /uploads = le_storage_obj = 100 = /uploads = le_storage_obj = eld_name = eld_name = 100 = 10 =2 = 75 = les/%Y/%m/%d = le_storage_obj = 100 = /var/images = r\.pdf$ = True = 100 = 100 = 50

Brought to you by

DJANGO 1.5 CHEATSHEET

ForeignKey on_delete options CASCADE PROTECT SET_NULL SET_DEFAULT SET(value) / SET(callback) DO_NOTHING cascades; default prevent related deletion Set to NULL Set to elds default Set to value / callback() No action (in Python)

IntegerField, PositiveIntegerField, PositiveSmallIntegerField

Model/Form eld validators MaxLengthValidator(max_length) MinLengthValidator(min_length) MaxValueValidator(max_value) MinValueValidator(min_value) RegexValidator(regex, message=None, code=None) URLValidator(verify_exists=False) validate_email validate_slug validate_ipv4_address (also _ipv6_, _ipv46_)

Not chainable

Chainable

Aggregation/annotation functions Avg(eld) Count(eld, distinct=False) Max(eld) Min(eld) Signals StdDev(eld, sample=False) Sum(eld) Variance(eld, sample=false)

Read the Docs


Create, host, and browse documentation. http://readthedocs.org/

django.db.models.signals pre_init, post_init(sender, args, kwargs) pre_save, post_save(sender, instance, using) pre_delete, post_delete(sender, instance, using) m2m_changed(sender, instance, action, reverse, model, pk_set, using) class_prepared(sender) post_syncdb(sender, app, created_models, verbosity, interactive) django.core.signals request_started, request_nished(sender) got_request_exception(sender, request)

django.test.signals settings_changed(sender, setting, value) template_rendered(sender, template, context) django.db.backends.signals connection_created(sender, connection) django.contrib.auth.signals user_logged_in, user_logged_out(sender, request, user) user_login_failed(sender, credentials) django.contrib.comments.signals comment_will_be_posted(sender, comment, request) comment_was_posted(sender, comment, request) comment_was_agged(sender, comment, ag, created, request)

Haystack

Find the needle you're looking for.

Modular search for Django. http://haystacksearch.org/ Intelligent migrations. http://south.aeracode.org/

Common eld options

We know Django. http://revsys.com/

Brought to you by

error_messages help_text initial label localize required validators widget

= {"code": "Message", } = "help text" = value = "eld label" = False = True = [validator, ] = WidgetClass Form elds

DJDT
All widgets attrs CheckboxInput check_test CheckboxSelectMultiple ClearableFileInput DateInput format DateTimeInput format FileInput

Django Debug Toolbar


Debug better, faster. http://django.me/djdt Form widgets

Tastypie
Creating delicious APIs for Django apps since 2010. http://tastypieapi.org/ Template lters add:"2" addslashes caprst center:"15" cut:" " date:"jS F Y H:i" default:"nothing" default_if_none:"nothing" dictsort:"key" dictsortreversed:"key" divisibleby:"4" escape escapejs lesizeformat rst x_ampersands oatformat oatformat:"3" force_escape get_digit:"2" iriencode join:"/" length length_is:"4" linebreaks linebreaksbr linenumbers ljust:"10" lower make_list phone2numeric pluralize pluralize:"es" pluralize:"y,ies" pprint random removetags:"span div" rjust:"10" safe safeseq slice:"10:20" slugify stringformat:"s" striptags time:"H:i" timesince timesince:from_date timeuntil timeuntil:from_date truncatecharsX:9 truncatewords:"10" truncatewords_html:"10" unordered_list upper urlencode urlencode:"/+" urlize urlizetrunc:"15" wordcount wordwrap:"20" yesno:"yeah,no,unknown" template a A b B c d D e E f F g G h H i j l L m M n N o O P r s S t T u U w W y Y

Datetime formatting strftime %p a.m. / p.m. AM / PM jan, feb, 2008-01-02T10:30:00.000123 Fri Mar 4 16:43:23 2011 01 - 31 Mon, Tue, UTC, CST (timezone name) (alternate long month) 1, 1:30 January, February, 1 - 12 0 - 23 01 - 12 00 - 23 00 - 59 (minutes) 1 - 31 001 - 365 Monday, Tuesday, (leap year?) 01 - 12 Jan, Feb, 1 - 12 Jan., Feb., March, (ISO-8601 week-numbering year) +0200 1 a.m., noon, 2:30 p.m. Thu, 21 Dec 2000 16:01:07 +0200 00 - 59 (seconds) st, nd, rd, th 28 - 31 EST, UTC, (microseconds) (unix timestamp) 0 (Sun.) - 6 (Sat.) 1 - 53 01 - 53 99 1999 03/04/11 16:43:23 0 - 365 (tz oset, seconds) (as dened in settings) (as dened in settings) (as dened in settings) (as dened in settings)

= {'class': 'fancy', } = callback(value)

%c %d %a

BooleanField, NullBooleanField CharField max_length min_length = 100 = 10

= "%Y-%m-%d" = "%Y-%m-%d %H:%M"

%B %m %I %H %M %j %A

ChoiceField, MultipleChoiceField choices = [(1, "Choice 1"), ] TypedChoiceField, TypedMultipleChoiceField choices = [(1, "Choice 1"), ] coerce = callback(value) empty_value = "" ModelChoiceField, ModelMultipleChoiceField queryset = Model.objects.all() empty_label = u"------" DateField input_formats DateTimeField input_formats DecimalField max_value min_value max_digits decimal_places EmailField FileField, ImageField FilePathField path recursive match FloatField max_value min_value IntegerField max_value min_value IPAddressField GenericIPAddressField protocol unpack_ipv4 RegexField regex max_length min_length SlugField max_length min_length TimeField input_formats URLField max_length min_length verify_exists validator_user_agent SplitDateTimeField input_date_formats input_time+_formats = both | IPv4 | IPv6 = False = r'\w+' = 100 = 10 = 100 = 10 = ["%H:%M:%S", ] = 100 = 10 = False = "Django/1.3" = ["%Y-%m-%d", ] = ["%H:%M:%S", ] = "/home/images" = True = r"\.pdf" = 100.0 = 10.0 = 100 = 10 = ["%Y-%m-%d", ] = ["%Y-%m%d %H:%M", ] = Decimal(100) = Decimal(10) = 10 =2

HiddenInput, MultipleHiddenInput MultiWidget NullBooleanSelect PasswordInput render_value RadioSelect Select SelectDateWidget years SelectMultiple SplitDateTimeWidget Textarea TextInput TimeInput format = "%H:%M:%S" = [2010, 2011, ] = False

DJANGO 1.5 CHEATSHEET

%b

%S

%Z

Celery
Distributed, asychronous task queue. http://celeryproject.org/

Template tags

%w %U %y %Y x X

{% block name %}{% endblock %} HttpRequest HttpResponse {% csrf_token %} {% cycle "row1" "row2" [as varname] [silent] %} __iter__() __init__(content=, {% debug %} body mimetype=None, {% extends "base.html" %} build_absolute_uri(path) status=200, {% lter force_escape|lower %}{% endlter %} COOKIES content_type=None) {% rstof var1 var2 "fallback" %} encoding __delitem__(header) {% for i in list [reversed] %}{% empty %}{% endfor %} GET, POST, REQUEST __getitem__(header) {{ forloop.counter }} FILES __setitem__(header, val) {{ forloop.counter0 }} get_full_path() delete_cookie(key, {{ forloop.revcounter }} get_host() path="/", {{ forloop.revcounter0 }} get_signed_cookie(key) domain=None) {{ forloop.rst }} is_ajax() ush() {{ forloop.last }} is_secure() has_header(header) {{ forloop.parentloop }} META set_cookie, set_signed_cookie( {% if condition %}{% elif condition %}{% else %}{% endif %} method key, value, {% ifchanged %}{% else %}{% endifchanged %} path max_age=None, {% include "other/template.html" [with who="Jane" [only]] %} path_info expires=None, {% load [foo bar from] other_library %} read(size=None) path="/", {% now "jS F Y H:i" %} readline(), readlines() domain=None, {% regroup people by gender as gender_list %} session secure=None, {% spaceless %}{% endspaceless %} urlconf httponly=True) {% templatetag openblock / closeblock / openvariable / user tell() closevariable / openbrace / closebrace / write(content) opencomment / closecomment %} View shortcuts (django.shortcuts) {% url path.to.view arg1 arg2 arg3=v1 arg4=v2 [as the_url] %} {% widthratio this_value max_value 100 %} render(request, template, context_dict={}, context_instance=RequestContext, content_type="text/html", {% verbatim %} {% endverbatim %} {% with alpha=1 beta=2 %}{% endwith %} status=200, current_app=None) redirect(to, permanent=False, *args, **kw) get_object_or_404(Model, **lookup) get_list_or_404(Model, **lookup)

z Z DATE_FORMAT DATETIME_FORMAT SHORT_DATE_FORMAT SHORT_DATETIME_FORMAT

django.test.TestCase client_class xtures urls multi_db = django.test.client = [x1.json, x2.json, ] = my.app.urls = False

assertContains, assertNotContains(resp, text, count=None, status_code=200, msg_prex='', html=False) assertFieldOutput(cls, valid, invalid, eld_args=None, eld_kwargs=None, empty_value='') assertFormError(resp, form, eld, errors, msg_prex='') assertHTMLEqual, assertHTMLNotEqual(html1, html2, msg=) assertXMLEqual, assertXMLNotEqual(xml1, xml2, msg=) assertQuerysetEqual(qs, values, transform=repr, ordered=True) assertRedirects(resp, url, status_code=302, target_status_code=200, msg_prex='') assertTemplateUsed, assertTemplateNotUsed(resp, tmpl) with self.assertNumQueries(num, func): ... with self.assertRaisesMessage(exe, msg): with self.settings(SETTING=new_value): ...

Find more details in Djangos ocial docs: http://django.me/<any object here>