0% found this document useful (0 votes)
225 views

Django 1.4 Cheatsheet PDF

This document provides information on common Django model and form field options, as well as QuerySet and model methods. It lists field types, options, and validators for models and forms. It also covers model relationships, lookups, aggregation, and QuerySet methods.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
225 views

Django 1.4 Cheatsheet PDF

This document provides information on common Django model and form field options, as well as QuerySet and model methods. It lists field types, options, and validators for models and forms. It also covers model relationships, lookups, aggregation, and QuerySet methods.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 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 managed order_with_respect_to ordering permissions proxy unique_together verbose_name verbose_name_plural = False = "applabel" = "table_name" = "space_name" = "eld_name" = False = "eld" = ["eld_name", ] = [("code", "text label"), ] = False = [("eld1", "eld2"), ] = "verbose name" = "plural verbose names"

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

http://django.me/<any object here>


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

Find more details in Djangos ocial docs:

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)

Brought to you by

DJANGO 1.4 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_) validate_comma_separated_integer_list

Not chainable

Chainable

= string = list / queryset = date / int / oat / decimal = (lower, upper) = int = bool = r^reg\. exp\.

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) 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

Datetime formatting

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

BooleanField, NullBooleanField CharField max_length min_length = 100 = 10

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

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.4 CHEATSHEET

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

HttpRequest __iter__() body build_absolute_uri(path) COOKIES encoding GET, POST, REQUEST FILES get_full_path() get_host() get_signed_cookie(key) is_ajax() is_secure() META method path path_info read(size=None) readline(), readlines() session urlconf user

HttpResponse __init__(content=, mimetype=None, status=200, content_type=None) __delitem__(header) __getitem__(header) __setitem__(header, val) delete_cookie(key, path="/", domain=None) ush() has_header(header) set_cookie, set_signed_cookie( key, value, max_age=None, expires=None, path="/", domain=None, secure=None, httponly=True) tell() write(content)

Creating delicious APIs for Django apps since 2010. template strftime http://tastypieapi.org/ a a.m. / p.m. A %p AM / PM Template lters b jan, feb, add:"2" pluralize B addslashes pluralize:"es" c 2008-01-02T10:30:00.000123 caprst pluralize:"y,ies" %c Fri Mar 4 16:43:23 2011 center:"15" pprint d %d 01 - 31 cut:" " random D %a Mon, Tue, date:"jS F Y H:i" removetags:"span div" e UTC, CST (timezone name) default:"nothing" rjust:"10" E (alternate long month) default_if_none:"nothing" safe f 1, 1:30 dictsort:"key" safeseq F %B January, February, dictsortreversed:"key" slice:"10:20" g %m 1 - 12 divisibleby:"4" slugify G 0 - 23 escape stringformat:"s" h %I 01 - 12 escapejs striptags H %H 00 - 23 lesizeformat time:"H:i" i %M 00 - 59 (minutes) rst timesince I x_ampersands timesince:from_date j 1 - 31 oatformat timeuntil %j 001 - 365 oatformat:"3" timeuntil:from_date l %A Monday, Tuesday, force_escape truncatecharsX:9 L (leap year?) get_digit:"2" truncatewords:"10" m 01 - 12 iriencode truncatewords_html:"10" M %b Jan, Feb, join:"/" unordered_list n 1 - 12 length upper N Jan., Feb., March, length_is:"4" urlencode o (ISO-8601 week-numbering year) linebreaks urlencode:"/+" O +0200 linebreaksbr urlize P 1 a.m., noon, 2:30 p.m. linenumbers urlizetrunc:"15" r Thu, 21 Dec 2000 16:01:07 +0200 ljust:"10" wordcount s %S 00 - 59 (seconds) lower wordwrap:"20" S st, nd, rd, th make_list yesno:"yeah,no,unknown" t 28 - 31 phone2numeric T %Z EST, UTC, u (microseconds) U (unix timestamp) Template tags w %w 0 (Sun.) - 6 (Sat.) {% block name %}{% endblock %} W 1 - 53 {% csrf_token %} %U 01 - 53 {% cycle "row1" "row2" [as varname] [silent] %} y %y 99 {% debug %} Y %Y 1999 {% extends "base.html" %} x 03/04/11 {% lter force_escape|lower %}{% endlter %} X 16:43:23 {% rstof var1 var2 "fallback" %} z 0 - 365 {% for i in list [reversed] %}{% empty %}{% endfor %} Z (tz oset, seconds) {{ forloop.counter }} DATE_FORMAT (as dened in settings) {{ forloop.counter0 }} DATETIME_FORMAT (as dened in settings) {{ forloop.revcounter }} SHORT_DATE_FORMAT (as dened in settings) {{ forloop.revcounter0 }} SHORT_DATETIME_FORMAT (as dened in settings) {{ forloop.rst }} django.test.TestCase {{ forloop.last }} client_class xtures urls multi_db = django.test.client = [x1.json, x2.json, ] = my.app.urls = False

{{ forloop.parentloop }} {% if condition %}{% elif condition %}{% else %}{% endif %} {% ifchanged %}{% else %}{% endifchanged %} {% include "other/template.html" [with who="Jane" [only]] %} {% load [foo bar from] other_library %} {% now "jS F Y H:i" %} {% regroup people by gender as gender_list %} {% spaceless %}{% endspaceless %} {% templatetag openblock / closeblock / openvariable / closevariable / openbrace / closebrace / 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", {% with alpha=1 beta=2 %}{% endwith %} status=200, current_app=None) Sentry redirect(to, permanent=False, *args, **kw) Track production exceptions as they happen. get_object_or_404(Model, **lookup) http://www.getsentry.com/ get_list_or_404(Model, **lookup)

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=) 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): ...

You might also like