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

Filters

Text formatting Dates & times Escaping humanize library

DJANGO CHEAT SHEET Version 1.5


|lower
|upper
|title
|date: format
|time: format
|timesince[: datetime]
|safe
|safeseq
|apnumber
|intcomma
|intword
|escape
|capfirst |timeuntil[: datetime] |force_escape |naturalday[: format]
Talented developers apply at www.mercurytide.co.uk/careers |slugify Lists |escapejs |naturaltime
|ljust: width |addslashes |ordinal
|length
|rjust: width |fix_ampersands
|length_is: length i18n library
|center: width
Template tags |wordwrap: width
|first |iriencode
|language_name
|last |urlencode[: safe_chars]
Built in comments library |wordcount |language_name_local
|random
|striptags |bidi
{% autoescape on|off %} — {% endautoescape %} {% comment_form_target %} |join: string General
{% block name %} — {% endblock %} {% get_comment_count for var as name %} |removetags: "p br" l10n library
|slice: "1:9" |default: value
Case sensitive.
{% comment %} — {% endcomment %} {% get_comment_form for var as name %} |make_list |default_if_none: value |localize
|cut: substring
{% csrf_token %} {% get_comment_list for var as name %} |unordered_list |dictsort: key |unlocalize
|linebreaks
{% cycle "even" "odd" [as name [silent]] %} {% get_comment_permalink comment [format_string] %} |dictsortreversed: key
|linebreaksbr Numbers tz library
{% cycle name %} {% render_comment_form for var %} |pprint
|linenumbers |add: number
{% debug %} {% render_comment_list for var %} |stringformat: format |localtime
|phone2numeric |divisibleby: number
{% extends template %} |yesno[: "yes,no[,none]"] |timezone: tz_name
flatpages library |truncatechars: count |filesizeformat
{% filter filter1|filter2 %} |utc
{% get_flatpages [url_prefix] as name %} |truncatewords: count |floatformat[: decimal_places]
{% firstof var1 var2 ... default %} 
Does not auto-escape |truncatewords_html: count |get_digit: position
i18n library
{% for var[...] in list %} — [{% empty %}] — {% endfor %} |urlize position 1 = 1’s, 2 = 10’s
{% blocktrans [context context_name]
forloop.counter forloop.counter0 |urlizetrunc: length |pluralize[: "y,ies”]
[with name=value ...] %} — {% endblocktrans %}
forloop.revcounter forloop.revcounter0
{% blocktrans count name=value [context, with etc.] %} —
forloop.first forloop.parentloop
{% plural %} — {% endblocktrans%}
Template date formats
forloop.last
{% get_available_languages as LANGUAGES %} Year AM & PM Localized
{% if expression %} — [{% elif expression %}] —
{% get_current_language as LANGUAGE_CODE %} y 13
[{% else %}] — {% endif %} a a.m. or p.m. DATETIME_FORMAT Long date & time
{% get_current_language_bidi as LANGUAGE_BIDI %}
Comparisons: == != < <= > >= in not in Y 2013 A AM or PM SHORT_DATETIME_FORMAT Short date & time
Boolean: and or not {% get_language_info for "en" as lang %}
Month Hour DATE_FORMAT Long date
{% ifchanged [var1] [var2 ...] %} — {% endifchanged %} lang.code lang.name
H 00 to 23 SHORT_DATE_FORMAT Short date
lang.name_local lang.bidi F January
{% include template [with name=value ... [only]] %} TIME_FORMAT Time
{% get_language_info for list_of_codes as lang %} G 0 to 23
{% load library ... %} E (localised full date form)
{% trans string [context context_name] [as name] [noop] %} h 01 to 12 Timezone
{% load tag ... from library %} M Jan
g 1 to 12 T TZ code: EST, CET
{% now [timeformat] %} l10n library b jan
Minutes e TZ name: GMT, -500, US/Eastern
{% regroup list by attr as name %} {% localize on|off %} — {% endlocalize %} N Jan. (A.P.)
i 00 to 59 O TZ offset: +0200
{% spaceless %} — {% endspaceless %} static library n 1 to 12
Seconds Z TZ offset (sec): -43200 to 43200
{% ssi path [parsed] %} m 01 to 12
{% get_media_prefix [as name] %}
{% templatetag openblock %}
s 00 to 59 Misc
{% get_static_prefix [as name] %}
Day I DST in effect: 1 or 0
open|close...block|variable|brace|comment {% static path [as name] %}
µs
{% url "[app:]viewname" [arg ...] [kwarg=value ...] [as name] %} d 01 to 31 u 000000 to 999999 L Is leap year: True or False
staticfiles library
{% verbatim [name] %} — {% endverbatim [name] %} j 1 to 31 Time z Day of year: 0 to 365
{% static path [as name] %} S suffix: st, nd, rd or th Days in month: 28 to 31
{% widthratio value maxvalue maxwidth %} f 1, 1:30 1 a.m. t
= value / maxvalue * maxwidth tz library P 1 a.m. 1:30 p.m., W Week number: 1 to 53
{% with name=value[...]%} — {% endwith %} {% get_current_timezone [as TIME_ZONE] %} Day of week o Week-numbering year: 2013
midnight , noon
{% localtime on|off %} — {% endlocaltime %} Standards
l Friday
{% timezone time_zone_name %} — {% endtimezone %} c
cache library D Fri ISO 8601: 2013-03-28T09:47:23.538501+02:00
{% cache seconds name [vary_by ...] %} — {% endcache %} webdesign library w 0 (Sun) to 6 (Sat) r RFC 2822: Thu, 21 Dec 2000 16:01:07 +0200
{% lorem [number] [w|p|b] [random] %} U Unix time: 1364471243
Form & widget Media Formsets
DJANGO CHEAT SHEET Version 1.5 class Media:
FormSetClass = formset_factory(form,
css = {"all|screen|print": (filenames), ... }
[extra=1,] [max_num=None],
js = (filenames)
[can_order=False], [can_delete=False],
[extend = True]
Form fields [formset=BaseFormSet])

Common kwargs Dates & Times Validators FormSetClass(data, [files,] [initial=list,]


required=True DateField [input_formats=iterable] [prefix=string])
MaxLengthValidator(length)
label=string TimeField [input_formats=iterable]
MinLengthValidator(length)
help_text=string DateTimeField [input_formats=iterable] Formset attributes
validate_email
initial=value_or_function SplitDateTimeField [input_date_formats=iterable] formset.empty_form
validate_slug
validators=list_of_validators [input_time_formats=iterable] formset.management_form
validate_url
widget=Widget_class Numbers formset.ordered_forms
RegexValidator([regex=" "],
error_messages=dict
IntegerField [max_value=int] [message="Enter a valid value”], Form attributes
localize=False
[min_value=int] [code="invalid"])
(e.g. localize dates, decimals) form.ORDER
FloatField [max_value=float] MaxValueValidator(value)
[min_value=float] MinValueValidator(value) form.DELETE
Boolean
DecimalField [max_digits=number] validate_ipv4_address
BooleanField
[decimal_places=number] validate_ipv6_address
NullBooleanField
[max_value=decimal] validate_ipv46_address
Strings [min_value=decimal] validate_comma_separated_integer_list
Files
CharField [min_length=number]
[max_length=number] FileField [max_length=number] (of filename)
Widgets
SlugField [min_length=number] [allow_empty_file=False] General Choices
[max_length=number] ImageField [max_length=number] (of filename) Select [choices=iterable]
TextInput
RegexField regex=regex [allow_empty_file=False] [format=date_format] NullBooleanSelect [choices=((1, "Unknown"),
PasswordInput
[min_length=number] FilePathField [path=directory_path] (2, "Yes"), (3, "No"))]
HiddenInput
[max_length=number] [recursive=False] RadioSelect [choices=iterable]
TextArea
[match=regex] SelectMultiple [choices=iterable]
Choices [allow_files=True] CheckboxSelectMultiple [choices=iterable]
Dates & times
ChoiceField choices=iterable [allow_folders=False] MultipleHiddenInput [choices=iterable]
TypedChoiceField choices=iterable Internet DateInput [format=date_format]
Files
[coerce=function] DateTimeInput [format=datetime_format]
EmailField [min_length=number]
[empty_value=" "] TimeInput [format=time_format] FileInput
[max_length=number] ClearableFileInput
MultipleChoiceField choices=iterable SplitDateTimeWidget [date_format=date_format]
URLField [min_length=number]
TypedMultipleChoiceField choices=iterable [time_format=time_format]
[max_length=number] Common kwargs
[coerce=function] SplitHiddenDateTimeWidget
IPAddressField (IPv4)
[empty_value=" "] [protocol="both"|"IPv4"|"IPv6"] SelectDateWidget [years=iterable] attrs=dict eg.{"class": "foo", "rows": "5"}
GenericIPAddressField
ModelChoiceField queryset=queryset (IPv4/IPv6) [unpack_ipv4=False]
[empty_label="------"]
Misc ModelForms & ModelFormSets
[cache_choices=False]
ModelMultipleChoiceField queryset=queryset ComboField [fields=tuple] ModelForm Meta attributes Factories
[cache_choices=False] MultiValueField [fields=tuple] modelform_factory(model, [form=FormClass,]
abstract=False exclude=tuple
[fields=tuple,] [exclude=tuple,] [widgets=dict])
error_messages keys app_label=string widgets=dict
{ "field": TextInput() }
modelformset_factory(model, queryset=queryset,]
db_table=string
required invalid (int, email, etc.) max_value missing (file) invalid_list [formset=BaseModelFormSet,] ...)
model=model
min_length invalid_date max_digits empty (file) inlineformset_factory(parent_model, child_model,
fields=tuple
max_length invalid_time max_decimal_places invalid_image [fk_name=field,] [can_delete=True,]
invalid_choice min_value max_whole_digits invalid_pk_value [formset=BaseInlineFormSet,] ...)
Model Meta attributes
abstract=False ordering=tuple
DJANGO CHEAT SHEET Version 1.5 app_label=string permissions=tuple
db_table=string proxy=False
db_tablespace=string unique_together=tuple
Internet get_latest_by=field_name index_together=tuple
Model fields showing defaults EmailField [max_length=75] managed=True verbose_name=string
Common kwargs URLField [max_length=200] order_with_respect_to=field_name verbose_name_plural=string
null=False help_text=string IPAddressField (IPv4)
blank=False primary_key=False GenericIPAddressField [protocol="both"|"IPv4"|"IPv6"] Validators
choices=iterable unique=False [unpack_ipv4=False]
MaxLengthValidator(length) MaxValueValidator(value)
db_column=name unique_for_date=date_field_name Files MinLengthValidator(length) MinValueValidator(value)
db_index=False unique_for_month=date_field_name
FileField upload_to=path_or_function validate_email validate_ipv4_address
default=value_or_function unique_for_year=date_field_name
[storage=storage] validate_slug validate_ipv6_address
editable=True verbose_name=string
[max_length=number] validate_url validate_ipv46_address
error_messages=dict validators=iterable
ImageField upload_to=path_or_function RegexValidator([regex=""], [message= validate_comma_separated_integer_list
Numbers [storage=storage] "Enter a valid value”], [code="invalid"])
AutoField primary_key=True (mandatory) [height_field=field_name]

Booleans
[width_field=field_name] QuerySets
[max_length=number]
BooleanField Methods that return QuerySets QuerySet & Queries
FilePathField path=path
NullBooleanField [match=regex] all() exact=value|None lt=value
Numbers [recursive=False] none() iexact=value lte=value
IntegerField (>= 32 bit) [allow_files=True] filter(query) contains=string in=iterable|queryset
PositiveIntegerField (>= 32 bit) [allow_folders=False] exclude(query) icontains=string range=(start, end)
SmallIntegerField (DB specific size) [max_length=100] order_by(field, ...) startswith=string year=year
PositiveSmallIntegerField (DB specific size) Relationships reverse() istartswith=string month=1 – 12
BigIntegerField (64 bit) annotate(aggregate_query) endswith=string day=1 – 31
ForeignKey model (or "self")
DecimalField max_digits=number distinct([field, ...]) iendswith=string week_day=
[limit_choices_to=dict_or_Q]
decimal_places=number values(field, ...) regex=pattern 1 (Sun) – 7 (Sat)
[related_name=string]
FloatField values_list(field, ..., [flat=False]) iregex=pattern isnull=boolean
[to_field=field_name]
dates(field, kind="year|month|day", gt=value search=
[on_delete=action]
Strings [order="ASC|DESC"]) gte=value mysql fulltext query
OneToOneField model (or "self")
CharField max_length=number select_related([field, ...])
[limit_choices_to=dict_or_Q] Aggregation functions
TextField prefetch_related([field, ...])
[related_name=string] Count(field, [distinct=False])
SlugField [max_length=50] defer(field, ...)
ManyToManyField [to_field=field_name] Sum(field)
CommaSeparatedIntegerField max_length=number only(field, ...)
[on_delete=action] Max(field)
using(database_alias)
Strings [parent_link=False] Min(field)
select_for_update([nowait=False])
CharField max_length=number error_messages keys Avg(field)
extra([select=...], [select_params=...], [tables=...],
TextField StdDev(field, [sample=False])
null [where=...], [params=...], [order_by=...])
SlugField [max_length=50] Variance(field, [sample=False])
blank
CommaSeparatedIntegerField max_length=number unique
invalid Other methods
Dates & times get(query) → instance aggregate(aggregate_query) → dict
invalid_choice
DateField [auto_now=False] invalid_date create(query) → instance update(field=value, ...)
[auto_now_add=False] get_or_create(query) → (instance created) delete()
on_delete actions
DateTimeField [auto_now=False] earliest([field_name]) → instance in_bulk(ids) → instances dict, keyed by id
[auto_now_add=False] CASCADE SET_DEFAULT latest([field_name]) → instance bulk_create(instances, [batch_size=number])
TimeField [auto_now=False] PROTECT SET(value_or_function) exists() → boolean iterator() → iterator
[auto_now_add=False] SET_NULL DO_NOTHING count() → number
DJANGO CHEAT SHEET Version 1.5

ModelAdmin
List columns Form contents Change List
list_display = field_names filter_horizontal = field_names get_ordering(self, request) → field_names
list_display_links = field_names filter_vertical = field_names get_list_display(self, request) → field_names
list_editable = field_names radio_fields = dict: get_list_display_links(self, request, list_display) → field_names
list_filter = field_names {'choice_field': HORIZONTAL|VERTICAL, ...}
get_list_filter(self, request) → field_names
fieldsets = dict: Mercurytide is built upon a foundation of great
search_fields = field_names get_changelist(self, request, **kwargs) → ChangeList_class
( people. We love all things digital, and our clients
date_hierarchy = field_name get_changelist_form(self, request, **kwargs) → ModelForm_class
(title|None, { benefit from our full-service delivery - from
List actions get_changelist_formset(self, request, **kwargs) → ModelFormSet_class
['fields': field_names,] strategy and thorough production to ongoing
actions = list ['classes': list,] get_paginator(self, request, queryset, per_page, orphans=0,
support. In order to keep up with the demand for
actions_on_top = True ['description': string,] allow_empty_first_page=True) → paginator
}), ..
our expert services, Mercurytide is growing.
actions_on_bottom = False Add/Change Form
)
actions_selection_counter = True
save_on_top = False get_readonly_fields(self, request, obj=None) → field_names You will join a culture of exceptional people, who
ordering = field_names
Form layout get_prepopulated_fields(self, request, obj=None) → prepopulated_fields_dict pride themselves on being up to speed with the
List options get_fieldsets(self, request, obj=None) → fieldsets_tuple latest technologies. Our forward-thinking staff
add_form_template = template
ordering = field_names get_form(self, request, obj=None, **kwargs) → form_class have created bespoke solutions for a wide variety
change_form_template = template
list_select_related = False get_inline_instances(self, request, obj=None) → inline_instances_tuple of clients, from local retailers to global market
change_list_template = template
list_per_page = 100 get_formsets(self, request, obj=None) → yields InlineModelAdmins leaders. We champion the strengths of our staff
delete_confirmation_template = template
list_max_show_all = 200 formfield_for_choice_field(self, db_field, request, **kwargs) → field
delete_selected_confirmation_template = template and fuel progress by learning from each other.
paginator = paginator_class formfield_for_foreignkey(self, db_field, request, **kwargs) → field
object_history_template = template
Form contents formfield_for_manytomany(self, db_field, request, **kwargs) → field Life at Mercurytide is never dull; we have a busy
Templates
fields = field_names calendar of work, plus social events for our staff.
add_form_template = template
exclude = field_names
change_form_template = template
InlineModelAdmin If you are talented and think that your skill set
inlines = inline_classes can benefit our clients, then drop us a line today.
change_list_template = template Standard subclasses
readonly_fields = field_names
delete_confirmation_template = template StackedInline
raw_id_fields = field_names Don’t forget be our friend on Facebook and link
delete_selected_confirmation_template = template TabularInline
prepopulated_fields = dict 
object_history_template = template up with us on LinkedIn.
{'slug': ('title',), ...}
Attributes & methods
form = form_class Queryset
formfield_overrides = dict model = model (mandatory) verbose_name = string
queryset(self, request) → queryset fk_name = field verbose_name_plural = string
save_as = False
form = ModelForm can_delete = True
Saving
formset = BaseInlineFormSet template = template
save_model(self, request, obj, form, is_change) – must call obj.save() extra = 1 get_formset(self, request, obj=None) →
delete_model(self, request, obj) – must call obj.delete() max_num = number BaseInlineFormSet_class
save_formset(self, request, form, formset, is_change) – must call formset.save()
save_related(self, request, form, formsets, is_change) - must call save() for each formset
AdminSite
Permissions
login_form = form
has_add_permission(self, request) → boolean
has_change_permission(self, request, obj=None) → boolean
index_template = template Talented developers apply at
login_template = template
has_delete_permission(self, request, obj=None) → boolean
logout_template = template
www.mercurytide.co.uk/careers
URLs password_change_template = template
get_urls(self) → urlpatterns password_change_done_template = template

Вам также может понравиться