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

Django 1.3 Cheatsheet

This document provides information about common model field options, ModelAdmin options and callbacks, and Model Meta options in Django. It lists field types like AutoField, BigIntegerField, BooleanField, CharField, CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField, and EmailField along with their common arguments. It also lists ModelAdmin options that can customize the admin interface and Model Meta options that can configure the model.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
348 views

Django 1.3 Cheatsheet

This document provides information about common model field options, ModelAdmin options and callbacks, and Model Meta options in Django. It lists field types like AutoField, BigIntegerField, BooleanField, CharField, CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField, and EmailField along with their common arguments. It also lists ModelAdmin options that can customize the admin interface and Model Meta options that can configure the model.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Common model field options Model fields ModelAdmin options & callbacks

Find more details in Django’s official docs:


null = False AutoField ➥ http://django.me/<any object here> actions = ["method", callback, …]

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


blank = False BigIntegerField actions_on_bottom = False
choices = [(1, “Choice 1”), …] actions_on_top = True
BooleanField, NullBooleanField QuerySet methods
db_column = “column_name” actions_selection_counter = True
db_index = False CharField add_form_template = 'add_form.html'
all()
Brought to you by

db_tablespace = “tablespace_name” max_length = 100 change_form_template = 'change_form.html'


annotate(**annotations)
default = value_or_callable CommaSeparatedIntegerField change_list_template = 'changelist.html',
dates(field, "year/month/day", "ASC/DESC")
error_messages = {”name”: “Message”, …}, max_length = 50 date_hierarchy = "date_field"
defer(*fields)
help_text = “long help text” DateField delete_confirmation_template = 'delete.html'
distinct()
primary_key = False delete_selected_confirmation_template = 'del.html'
DateTimeField exclude(**lookups)
unique = False exclude = ["field_name", …]
filter(**lookups)

Chainable
unique_for_date = “date_field” DecimalField fields = ["field_name", …]
none()
unique_for_month = “month_field” max_digits = 10 fieldsets
only(*fields)
verbose_name = “Field Name” decimal_places =2 = [("Name", {"fields": ["field_name", …]}), …]
order_by(*fields)
validators = [validator_obj, …] EmailField filter_horizontal = ["m2m_field", …]
raw(sql, params)
max_length = 75 reverse() filter_vertical = ["m2m_field", …]
Model Meta options form = ModelFormClass
FileField select_related(‘field’, ‘field2’, …, depth=1)
using(“db_alias”) formfield_overrides
abstract = False upload_to = “files/%Y/%m/%d”
values(*fields) = {TextField: {"widget": MyWidget}, …}
app_label = "applabel" storage = file_storage_obj
values_list(*fields) inlines = [InlineClass, …]
db_table = "table_name" max_length = 100
values_list(field, flat=True) list_display = ["field_name", callable, …]
db_tablespace = "space_name" FilePathField list_display_links = ['field_name', …]
get_latest_by = "field_name" path = “/var/images” list_editable = ['field_name', …]
managed = False match = r”\.pdf$” get(**lookups) list_filter = ['field_name', …]
order_with_respect_to = "field" recursive = True create(**attributes) list_per_page = 100
ordering = ["field_name", …] max_length = 100 get_or_create(**attributes, defaults={}) list_select_related = False

Not chainable
permissions = [("code", "text label"), …] count() object_history_template = 'admin/history.html',
FloatField
proxy = False in_bulk(id_list) ordering = ['field_name']
unique_together = [("field1", "field2"), …] FileField iterator()
upload_to = “/uploads” paginator = Paginator
verbose_name = "verbose name" latest(field) prepopulated_fields = {'slug': ['title'], …}
verbose_name_plural = "plural verbose names" storage = file_storage_obj aggregate(**aggregations)
max_length = 100 radio_fields = {'fk_field': admin.HORIZONTAL, …}
exists() raw_id_fields = ['fk_or_m2m_field', …]
Model relationships ImageField update(**attributes) readonly_fields = ['field_name', …]
upload_to = “/uploads” delete() save_as = False
ForeignKey(OtherModel) storage = file_storage_obj save_on_top = False
related_name = “things” height_field = “field_name” Lookups
search_fields = ['field_name']
limit_choices_to = Q(foo=”bar”, ...) width_field = “field_name”
to_field = “key_field_name” max_length = 100 exact, iexact = “string”
on_delete = (on_delete option) contains, icontains = “string” add_view(self, request, form_url='', extra_context={})
IntegerField, PositiveIntegerField, PositiveSmallIntegerField startswith, endswith,
DJANGO 1.3 CHEATSHEET

ManyToManyField(OtherModel) changelist_view(self, request, extra_context={})


IPAddressField istartswith, iendswith = “string”
related_name = “things” change_view(self, request, object_id, extra_context={})
SlugField in = list / queryset delete_model(self, request, obj)
limit_choices_to = Q(foo=”bar”, ...) gt, lt, gte, lte = date / int / float / decimal
to_field = “key_field_name” max_length = 100 delete_view(self, request, object_id, extra_context={})
range = (lower, upper) formfield_for_choice_field(self, db_field, request, **kw)
symmetrical = True, SmallIntegerField
year, month, day = int formfield_for_foreignkey(self, db_field, request, **kw)
through = RelationshipModel TextField isnull = bool
db_table = “table_name” formfield_for_manytomany(self, db_field, request, **kw)
TimeField regex, iregex = r”^reg\. exp\.” get_paginator(self, queryset, per_page, orphans=0,
OneToOneField(OtherModel)
URLField allow_empty_first_page=True)
parent_link = False Aggregation/annotation functions
verify_exists = False get_readonly_fields(self, request, obj=None)
related_name = “thing”
get_urls(self)
limit_choices_to = Q(foo=”bar”, ...) Avg(field) StdDev(field, sample=False)
ForeignKey on_delete options has_add_permission(self, request)
to_field = “key_field_name” Count(field, distinct=False) Sum(field)
has_change_permission(self, request, obj=None)
on_delete = (on_delete option) Max(field) Variance(field, sample=false)
CASCADE cascades; default has_delete_permission(self, request, obj=None)
Min(field)
PROTECT prevent related deletion history_view(self, request, object_id, extra_context={})
Haystack
Find the needle you're looking for.
SET_NULL
SET_DEFAULT
Set to NULL
Set to field’s default Read the Docs
message_user(self, request, message)
queryset(self, request)
Intelligent migrations. Modular search for Django SET(value) / SET(callback) Set to value / callback() Create, host, and browse documentation. save_formset(self, request, form, formset, change)
DO_NOTHING No action (in Python) http://readthedocs.org/ save_model(self, request, obj, form, change)
http://south.aeracode.org/ http://haystacksearch.org/
ABSOLUTE_URL_OVERRIDES CSRF_COOKIE_NAME DEBUG FILE_UPLOAD_TEMP_DIR MONTH_DAY_FORMAT SHORT_DATE_FORMAT
ADMIN_FOR CSRF_FAILURE_VIEW DECIMAL_SEPARATOR FIRST_DAY_OF_WEEK NUMBER_GROUPING SHORT_DATETIME_FORMAT
ADMIN_MEDIA_PREFIX DATABASES DEFAULT_CHARSET FIXTURE_DIRS PASSWORD_RESET_TIMEOUT_DAYS SITE_ID
ADMINS {"ENGINE" DEFAULT_CONTENT_TYPE FORMAT_MODULE_PATH PREPEND_WWW STATIC_ROOT
ALLOWED_INCLUDE_ROOTS "HOST" DEFAULT_FILE_STORAGE IGNORABLE_404_ENDS PROFANITIES_LIST STATIC_URL
APPEND_SLASH "NAME" DEFAULT_FROM_EMAIL IGNORABLE_404_STARTS RESTRUCTUREDTEXT_FILTER_SETTINGS TEMPLATE_CONTEXT_PROCESSORS
AUTHENTICATION_BACKENDS "OPTIONS" DEFAULT_INDEX_TABLESPACE INSTALLED_APPS ROOT_URLCONF TEMPLATE_DEBUG
AUTH_PROFILE_MODULE "PASSWORD" DEFAULT_TABLESPACE INTERNAL_IPS SECRET_KEY TEMPLATE_DIRS
CACHES "PORT" DISALLOWED_USER_AGENTS LANGUAGE_CODE SEND_BROKEN_LINK_EMAILS TEMPLATE_LOADERS
Settings

{"BACKEND" "USER"} EMAIL_BACKEND LANGUAGE_COOKIE_NAME SERIALIZATION_MODULES TEMPLATE_STRING_IF_INVALID


"KEY_FUNCTION" TEST_CHARSET EMAIL_FILE_PATH LANGUAGES SERVER_EMAIL TEST_RUNNER
"KEY_PREFIX" TEST_COLLATION EMAIL_HOST LOCALE_PATHS SESSION_COOKIE_AGE THOUSAND_SEPARATOR
"LOCATION" TEST_DEPENDENCIES EMAIL_HOST_PASSWORD LOGGING SESSION_COOKIE_DOMAIN TIME_FORMAT
"OPTIONS" TEST_MIRROR EMAIL_HOST_USER LOGGING_CONFIG SESSION_COOKIE_HTTPONLY TIME_INPUT_FORMATS
"TIMEOUT" TEST_NAME EMAIL_PORT LOGIN_REDIRECT_URL SESSION_COOKIE_NAME TIME_ZONE
"VERSION"} TEST_USER EMAIL_SUBJECT_PREFIX LOGIN_URL SESSION_COOKIE_PATH URL_VALIDATOR_USER_AGENT
CACHE_MIDDLEWARE_ALIAS DATABASE_ROUTERS EMAIL_USE_TLS LOGOUT_URL SESSION_COOKIE_SECURE USE_ETAGS
CACHE_MIDDLEWARE_ANONYMOUS_ONLY DATE_FORMAT FILE_CHARSET MANAGERS SESSION_ENGINE USE_I18N
CACHE_MIDDLEWARE_KEY_PREFIX DATE_INPUT_FORMATS FILE_UPLOAD_HANDLERS MEDIA_ROOT SESSION_EXPIRE_AT_BROWSER_CLOSE USE_L10N
CACHE_MIDDLEWARE_SECONDS DATETIME_FORMAT FILE_UPLOAD_MAX_MEMORY_SIZE MEDIA_URL SESSION_FILE_PATH USE_THOUSAND_SEPARATOR
CSRF_COOKIE_DOMAIN DATETIME_INPUT_FORMATS FILE_UPLOAD_PERMISSIONS MIDDLEWARE_CLASSES SESSION_SAVE_EVERY_REQUEST YEAR_MONTH_FORMAT
Common field options Form widgets Django Debug Toolbar Datetime formatting

error_messages = {"code": "Message", …} All widgets DJDT Debug better, faster. template strftime

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


http://django.me/djdt
help_text = "help text" attrs = {'class': 'fancy', …} a a.m. / p.m.
initial = value CheckboxInput Template filters A %p AM / PM
label = "field label" check_test = callback(value) b jan, feb, …
localize = False add:"2" phone2numeric
Brought to you by

CheckboxSelectMultiple B
required = True addslashes pluralize
validators = [validator, …] ClearableFileInput c 2008-01-02T10:30:00.000123
capfirst pluralize:"es"
widget = WidgetClass DateInput %c Fri Mar 4 16:43:23 2011
center:"15" pluralize:"y,ies"
format = "%Y-%m-%d" cut:" " pprint d %d 01 - 31
Form fields date:"jS F Y H:i" random D %a Mon, Tue, …
DateTimeInput
format = "%Y-%m-%d %H:%M" default:"nothing" removetags:"span div" E (alternate long month)
BooleanField default_if_none:"nothing" rjust:"10"
FileInput f 1, 1:30
NullBooleanField dictsort:"key" safe F %B January, February, …
HiddenInput, MultipleHiddenInput dictsortreversed:"key" safeseq
CharField g %m 1 - 12
max_length = 100 MultiWidget divisibleby:"4" slice:"10:20"
G 0 - 23
min_length = 10 NullBooleanSelect escape slugify
escapejs stringformat:"s" h %I 01 - 12
ChoiceField PasswordInput H %H 00 - 23
filesizeformat striptags
choices = [(1, "Choice 1"), …] render_value = False first time:"H:i" i %M 00 - 59 (minutes)
TypedChoiceField RadioSelect fix_ampersands timesince I
choices = [(1, "Choice 1"), …] Select floatformat timesince:from_date j 1 - 31
coerce = callback(value) floatformat:"3" timeuntil
empty_value = "" SelectDateWidget %j 001 - 365
force_escape timeuntil:from_date
years = [2010, 2011, …] l %A Monday, Tuesday, …
MultipleChoiceField get_digit:"2" truncatewords:"10"
SelectMultiple L (leap year?)
choices = [(1, "Choice 1"), …] iriencode truncatewords_html:"10"
SplitDateTimeWidget join:"/" unordered_list m 01 - 12
TypedMultipleChoiceField
choices = [(1, "Choice 1"), …] Textarea length upper M %b Jan, Feb, …
coerce = callback(value) TextInput length_is:"4" urlencode n 1 - 12
empty_value = "" linebreaks urlencode:"/+" N Jan., Feb., March, …
TimeInput linebreaksbr urlize
DateField format = "%H:%M:%S" O +0200
linenumbers urlizetrunc:"15"
input_formats = ["%Y-%m-%d", …] P 1 a.m., noon, 2:30 p.m.
Model/Form field validators ljust:"10" wordcount
DateTimeField lower wordwrap:"20" r Thu, 21 Dec 2000 16:01:07 +0200
input_formats = ["%Y-%m%d %H:%M", …] MaxLengthValidator(max_length) make_list yesno:"yeah,no,unknown" s %S 00 - 59 (seconds)
DecimalField MinLengthValidator(min_length) S st, nd, rd, th
Template tags
max_value = Decimal(100) MaxValueValidator(max_value) t 28 - 31
min_value = Decimal(10) MinValueValidator(min_value) T %Z EST, UTC, …
{% block name %}…{% endblock %}
max_digits = 10 RegexValidator(regex, message=None, code=None) u (microseconds)
{% csrf_token %}
DJANGO 1.3 CHEATSHEET

decimal_places =2 URLValidator(verify_exists=False) {% cycle "row1" "row2" [as varname] [silent] %} U (unix timestamp)
EmailField validate_email {% debug %} w %w 0 (Sun.) - 6 (Sat.)
validate_slug
FileField {% extends "base.html" %} W 1 - 53
validate_ipv4_address {% filter force_escape|lower %}…{% endfilter %}
FilePathField validate_comma_separated_integer_list %U 01 - 53
{% firstof var1 var2 "fallback" %}
path = "/home/images" y %y 99
{% for i in list [reversed] %}…{% empty %}…{% endfor %}
recursive = True Y %Y 1999
match = r"\.pdf"
Django Packages {{ forloop.counter }}
Find reusable apps and tools for your Django site. {{ forloop.counter0 }} x 03/04/11
FloatField http://djangopackages.com/ {{ forloop.revcounter }} X 16:43:23
max_value = 100.0 {{ forloop.revcounter0 }} z 0 - 365
min_value = 10.0 {{ forloop.first }}
Signals Z (tz offset, seconds)
ImageField {{ forloop.last }}
DATE_FORMAT (as defined in settings)
IntegerField django.db.models.signals {{ forloop.parentloop }}
{% if condition %}…{% else %}…{% endif %} DATETIME_FORMAT (as defined in settings)
max_value = 100 pre_init(sender, args, kwargs)
post_init(sender, args, kwargs) {% ifchanged %}…{% else %}…{% endifchanged %} SHORT_DATE_FORMAT (as defined in settings)
min_value = 10
pre_save(sender, instance, using) {% include "other/template.html" [with who="Jane" … [only]] %} SHORT_DATETIME_FORMAT (as defined in settings)
IPAddressField {% load [foo bar … from] other_library %}
post_save(sender, instance, created, using) HttpRequest HttpResponse
RegexField pre_delete(sender, instance, using) {% now "jS F Y H:i" %}
regex = r'\w+' post_delete(sender, instance, using) {% regroup people by gender as gender_list %}
__iter__() __init__(content=’’,
max_length = 100 m2m_changed(sender, instance, action, reverse, {% spaceless %}…{% endspaceless %}
build_absolute_uri(path) mimetype=None,
min_length = 10 model, pk_set, using) {% templatetag openblock / closeblock / openvariable /
COOKIES status=200,
SlugField class_prepared(sender) closevariable / openbrace / closebrace /
encoding content_type=None)
max_length = 100 post_syncdb(sender, app, created_models, opencomment / closecomment %}
FILES __delitem__(header)
min_length = 10 verbosity, interactive) {% url path.to.view arg1 arg2 arg3=v1 arg4=v2 [as the_url] %}
GET __getitem__(header)
{% widthratio this_value max_value 100 %}
TimeField django.core.signals get_full_path() __setitem__(header, val)
{% with alpha=1 beta=2 … %}…{% endwith %}
input_formats = ["%H:%M:%S", …] request_started(sender) get_host() delete_cookie(key,
URLField request_finished(sender) is_ajax() path="/",
max_length = 100 got_request_exception(sender, request) Celery is_secure() domain=None)
min_length = 10 django.test.signals Distributed, asychronous task queue. META flush()
verify_exists = False template_rendered(sender, template, context) http://celeryproject.org/ method has_header(header)
validator_user_agent = "Django/1.3" path set_cookie(key, value,
django.db.backends.signals
django.shortcuts path_info max_age=None,
SplitDateTimeField connection_created(sender, connection)
POST expires=None,
input_date_formats = ["%Y-%m-%d", …] django.contrib.auth.signals raw_post_data path="/",
render(request, template, context_dict={},
input_time+_formats = ["%H:%M:%S", …] user_logged_in(sender, request, user) read(size=None) domain=None,
context_instance=RequestContext, content_type="text/html",
ModelChoiceField user_logged_out(sender, request, user) status=200, current_app=None) readline() secure=None,
queryset = Model.objects.all() django.contrib.comments.signals render_to_response(template, context_dict={}, readlines() httponly=False)
empty_label = u"------" comment_will_be_posted(sender, comment, request) context_instance=Contact, mimetype="text/html") REQUEST tell()
ModelMultipleChoiceField comment_was_posted(sender, comment, request) redirect(to, permanent=False, *args, **kw) session write(content)
queryset = Model.objects.all() comment_was_flagged(sender, comment, flag, get_object_or_404(Model, **lookup) urlconf
created, request) get_list_or_404(Model, **lookup) user

You might also like