When a developer has learned how to use a technology, it is often necessary to search for new information or syntax. He/she can waste a lot of time doing this. The purpose of this appendix is to provide a quick reference for Django developers.
The following sections cover a nonexhaustive list of the field types in models.
The model fields are those that will be saved in the database. Depending on the database system selected, the type field may be different depending on the database used.
The types are specified with their options in the following manner:
Type (option1 = example_data, option2 = example_data) [information]
Fields presented in this section are numeric fields such as integers and decimals:
The descriptions of the options are as follows:
This section contains the types of fields that contain strings:
CharField (max_length = 250)
TextField (max_length = 250)
: This field has the distinction of being presented as a<textarea>
tag in the Django formsEmailField (max_length = 250)
: This field isCharField
that contains an e-mail validator for Django forms
The description of the option is as follows:
max_length
: This sets the maximum number of characters that compose the string
This section contains the types of fields that contain temporal data:
DateField (auto_now = false
,auto_now_add = true)
DateTimeField (auto_now = false
,auto_now_add = true)
TimeField (auto_now = false
,auto_now_add = true)
The descriptions of the options are as follows:
This section contains the types of fields that do not belong to the previous categories:
BooleanField()
FileField: (upload_to = "path", max_length="250")
: This field is used to store files on the serverImageField(upload_to = "path", max_length="250", height_field =height_img, width_field= width_img)
: This field corresponds toFileField
but imparts special treatment to images such as storing the image's height and width
The descriptions of the options are as follows:
Upload_to
: This defines the folder that will store the files corresponding to this field.max_length
: TheFileField
andImageField
fields are actually text fields that store the path and name of the uploaded file.height_field
andwidth_field
: These take an integer field of the model as an argument. This field is used to store the size of the image.
This section contains the types of fields that define the relationships between models:
ForeignKey (model, related_name = "foreign_key_for_dev", to_field="field_name", limit_choices_to=dict_or_Q, on_delete=)
OneToOneField (model, related_name = "foreign_key_for_dev", to_field="field_name", limit_choices_to=dict_or_Q, on_delete=)
ManyToManyField (model, related_name = "foreign_key_for_dev", to_field="field_name", limit_choices_to=dict_or_Q, on_delete=)
The descriptions of the options are as follows:
model
: Here, you must specify the name of the model class you want to use.related_name
: This allows you to name the relationship. It is essential when multiple relationships to the same model exist.to_field
: This defines a relationship to a specific field of the model. By default, Django creates a relationship to the primary key.on_delete
: The database action on the removal of a field can beCASCADE
,PROTECT
,SET_NULL
,SET_DEFAULT
, andDO_NOTHING
.limit_choices_to
: This defines the queryset that restricts records for the relationship.
The model meta attributes are to be defined in a meta class in the model in the following way:
class Product(models.Model): name = models.CharField() class Meta: verbose_name = "product"
The following attributes are used to define information about the model in which they are placed:
The following options are common to all the fields of a model:
default
: This sets a default value for the field.null
: This enables the null value for the field and makes an optional relationship if this option is defined on a relationship field.blank
: This enables you to leave the field empty.error_messages
: This specifies a series of error messages.help_text
: This sets a help message.unique
: This defines a field that does not contain duplicates.verbose_name
: This defines a field name that is readable by a human. Do not put a capital letter first; Django will do it automatically.choices
: This defines the number of possible choices for the field.db_column
: This sets the name of the field created in the database.
It is possible to use all types of field models in the forms. Indeed, some types of model fields have been created for a particular use in forms. For example, the TextField
model field has nothing different from CharField
except the fact that by default, in the form, the TextField
field displays a <textarea>
tag and a <input type="text">
name. So, you can write a form field as follows:
field1 = forms.TextField()
The following options are common to all the form fields:
error_messages
: This specifies a series of error messageshelp_text
: This sets a help messagerequired
: This defines a field that must be filledinitial
: This sets the default value for the fieldvalidators
: This defines a particular validator that validates the field valuewidget
: This defines a specific widget for the field
Widgets allow you to define HTML code that renders form fields. We'll explain what widgets can generate as HTML code, as follows:
TextInput
: This corresponds to<input type="text" />
Textarea
: This corresponds to<textarea></textarea>
PasswordInput
: This corresponds to<input type="password" />
RadioSelect
: This corresponds to<input type="radio" />
Select
: This corresponds to<select><option></option></select>
CheckboxInput
: This corresponds to<input type="checkbox" />
FileInput
: This corresponds to<input type="file" />
HiddenInput
: This corresponds to<input type="hidden" />
The following is a partial list of the error messages that can be set when form fields are entered incorrectly:
required
: This message is displayed when the user does not fill data in the fieldmin_length
: This message is displayed when the user has not supplied enough datamax_length
: This message is displayed when the user has exceeded the size limit of a fieldmin_value
: This message is displayed when the value entered by the user is too lowmax_value
: This message is displayed when the value entered by the user is too high
Common options for the form fields
The following options are common to all the form fields:
error_messages
: This specifies a series of error messageshelp_text
: This sets a help messagerequired
: This defines a field that must be filledinitial
: This sets the default value for the fieldvalidators
: This defines a particular validator that validates the field valuewidget
: This defines a specific widget for the field
Widgets allow you to define HTML code that renders form fields. We'll explain what widgets can generate as HTML code, as follows:
TextInput
: This corresponds to<input type="text" />
Textarea
: This corresponds to<textarea></textarea>
PasswordInput
: This corresponds to<input type="password" />
RadioSelect
: This corresponds to<input type="radio" />
Select
: This corresponds to<select><option></option></select>
CheckboxInput
: This corresponds to<input type="checkbox" />
FileInput
: This corresponds to<input type="file" />
HiddenInput
: This corresponds to<input type="hidden" />
The following is a partial list of the error messages that can be set when form fields are entered incorrectly:
required
: This message is displayed when the user does not fill data in the fieldmin_length
: This message is displayed when the user has not supplied enough datamax_length
: This message is displayed when the user has exceeded the size limit of a fieldmin_value
: This message is displayed when the value entered by the user is too lowmax_value
: This message is displayed when the value entered by the user is too high
The widget form
Widgets allow you to define HTML code that renders form fields. We'll explain what widgets can generate as HTML code, as follows:
TextInput
: This corresponds to<input type="text" />
Textarea
: This corresponds to<textarea></textarea>
PasswordInput
: This corresponds to<input type="password" />
RadioSelect
: This corresponds to<input type="radio" />
Select
: This corresponds to<select><option></option></select>
CheckboxInput
: This corresponds to<input type="checkbox" />
FileInput
: This corresponds to<input type="file" />
HiddenInput
: This corresponds to<input type="hidden" />
The following is a partial list of the error messages that can be set when form fields are entered incorrectly:
required
: This message is displayed when the user does not fill data in the fieldmin_length
: This message is displayed when the user has not supplied enough datamax_length
: This message is displayed when the user has exceeded the size limit of a fieldmin_value
: This message is displayed when the value entered by the user is too lowmax_value
: This message is displayed when the value entered by the user is too high
Error messages (forms and models)
The following is a partial list of the error messages that can be set when form fields are entered incorrectly:
required
: This message is displayed when the user does not fill data in the fieldmin_length
: This message is displayed when the user has not supplied enough datamax_length
: This message is displayed when the user has exceeded the size limit of a fieldmin_value
: This message is displayed when the value entered by the user is too lowmax_value
: This message is displayed when the value entered by the user is too high
When a developer develops templates, he/she regularly needs to use the template language and filters.
The following are the key elements of the template language:
{% autoescape on OR off %} {% endautoescape %}
: This automatically starts the auto-escape feature that helps protect the browser of the displayed data (XSS).{% block block_name %} {% endblock %}
: This sets the blocks that can be filled by templates that inherit from them.{% comment %} {% endcomment %}
: This sets a comment that will not be sent to the user as HTML.{% extends template_name %}
: This overrides a template.{% spaceless %}
: This removes all the whitespaces between the HTML tags.{% include template_name %}
: This includes a template namedtemplate_name
in the current template. The blocks included templates that cannot be redefined.
This section shows you how to loop through a dictionary. The steps involved in looping are as follows:
{% for var in list_var %}
: This allows looping in thelist_var
dictionary{% empty %}
: This displays the subsequent code if the dictionary is empty{% endfor %}
: This indicates the end of a loop
This section shows how to execute a conditional statement:
{% if cond %}
: This line checks the condition and discusses the following code when enabled.{% elif cond %}
: This line checks another condition if the first has not been verified. If this condition is satisfied, the following code will be processed.{% else %}
: This line will process the following code if none of the previous conditions have been validated.{% endif %}
: This line ends the processing of conditions.
The following are the different template filters:
addslashes
: This adds slashes before quotescapfirst
: This capitalizes the first characterlower
: This converts the text into lowercaseupper
: This converts the text into uppercasetitle
: This capitalizes all the first characters of each wordcut
: This removes all the values of the argument from the given string, for example,{{ value|cut:"*" }}
removes all the*
characterslinebreaks
: This replaces line breaks in text with the appropriate HTML tagsdate
: This displays a formatted date, for example,{{ value|date:"D d M Y" }}
will displayWed 09 Jan 2008
pluralize
: This allows you to display plurals, shown as follows:You have {{ nb_products }} product{{ nb_products|pluralize }} in our cart. I received {{ nb_diaries }} diar{{ nb_diaries|pluralize:"y,ies" }}.
random
: This returns a random element from the listlinenumbers
: This displays text with line numbers at the left-hand sidefirst
: This displays the first item in the listlast
: This displays the last item in the listsafe
: This sets a non-escape valueescape
: This escapes an HTML stringescapejs
: This escapes characters to use in JavaScript stringsdefault
: This defines a default value if the original value equalsNone
orempty
; for example, with{{ value|default:"nothing" }}
, if the value is""
, it will displaynothing
.dictsort
: This sorts the dictionary in the ascending order of the key; for example,{{ value|dictsort:"price"}}
will sort the dictionary byprice
dictsortreversed
: This is used to sort the dictionary in the descending order of the keyfloatformat
: This formats a float value, and the following are the examples:When 45.332
is the value,{{ value|floatformat:2 }}
displays45.33
- When
45.00
is the value,{{ value|floatformat:"-2" }}
displays45
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods:
Template tags
The following are the key elements of the template language:
{% autoescape on OR off %} {% endautoescape %}
: This automatically starts the auto-escape feature that helps protect the browser of the displayed data (XSS).{% block block_name %} {% endblock %}
: This sets the blocks that can be filled by templates that inherit from them.{% comment %} {% endcomment %}
: This sets a comment that will not be sent to the user as HTML.{% extends template_name %}
: This overrides a template.{% spaceless %}
: This removes all the whitespaces between the HTML tags.{% include template_name %}
: This includes a template namedtemplate_name
in the current template. The blocks included templates that cannot be redefined.
This section shows you how to loop through a dictionary. The steps involved in looping are as follows:
{% for var in list_var %}
: This allows looping in thelist_var
dictionary{% empty %}
: This displays the subsequent code if the dictionary is empty{% endfor %}
: This indicates the end of a loop
This section shows how to execute a conditional statement:
{% if cond %}
: This line checks the condition and discusses the following code when enabled.{% elif cond %}
: This line checks another condition if the first has not been verified. If this condition is satisfied, the following code will be processed.{% else %}
: This line will process the following code if none of the previous conditions have been validated.{% endif %}
: This line ends the processing of conditions.
The following are the different template filters:
addslashes
: This adds slashes before quotescapfirst
: This capitalizes the first characterlower
: This converts the text into lowercaseupper
: This converts the text into uppercasetitle
: This capitalizes all the first characters of each wordcut
: This removes all the values of the argument from the given string, for example,{{ value|cut:"*" }}
removes all the*
characterslinebreaks
: This replaces line breaks in text with the appropriate HTML tagsdate
: This displays a formatted date, for example,{{ value|date:"D d M Y" }}
will displayWed 09 Jan 2008
pluralize
: This allows you to display plurals, shown as follows:You have {{ nb_products }} product{{ nb_products|pluralize }} in our cart. I received {{ nb_diaries }} diar{{ nb_diaries|pluralize:"y,ies" }}.
random
: This returns a random element from the listlinenumbers
: This displays text with line numbers at the left-hand sidefirst
: This displays the first item in the listlast
: This displays the last item in the listsafe
: This sets a non-escape valueescape
: This escapes an HTML stringescapejs
: This escapes characters to use in JavaScript stringsdefault
: This defines a default value if the original value equalsNone
orempty
; for example, with{{ value|default:"nothing" }}
, if the value is""
, it will displaynothing
.dictsort
: This sorts the dictionary in the ascending order of the key; for example,{{ value|dictsort:"price"}}
will sort the dictionary byprice
dictsortreversed
: This is used to sort the dictionary in the descending order of the keyfloatformat
: This formats a float value, and the following are the examples:When 45.332
is the value,{{ value|floatformat:2 }}
displays45.33
- When
45.00
is the value,{{ value|floatformat:"-2" }}
displays45
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods:
Loops in dictionaries
This section shows you how to loop through a dictionary. The steps involved in looping are as follows:
{% for var in list_var %}
: This allows looping in thelist_var
dictionary{% empty %}
: This displays the subsequent code if the dictionary is empty{% endfor %}
: This indicates the end of a loop
This section shows how to execute a conditional statement:
{% if cond %}
: This line checks the condition and discusses the following code when enabled.{% elif cond %}
: This line checks another condition if the first has not been verified. If this condition is satisfied, the following code will be processed.{% else %}
: This line will process the following code if none of the previous conditions have been validated.{% endif %}
: This line ends the processing of conditions.
The following are the different template filters:
addslashes
: This adds slashes before quotescapfirst
: This capitalizes the first characterlower
: This converts the text into lowercaseupper
: This converts the text into uppercasetitle
: This capitalizes all the first characters of each wordcut
: This removes all the values of the argument from the given string, for example,{{ value|cut:"*" }}
removes all the*
characterslinebreaks
: This replaces line breaks in text with the appropriate HTML tagsdate
: This displays a formatted date, for example,{{ value|date:"D d M Y" }}
will displayWed 09 Jan 2008
pluralize
: This allows you to display plurals, shown as follows:You have {{ nb_products }} product{{ nb_products|pluralize }} in our cart. I received {{ nb_diaries }} diar{{ nb_diaries|pluralize:"y,ies" }}.
random
: This returns a random element from the listlinenumbers
: This displays text with line numbers at the left-hand sidefirst
: This displays the first item in the listlast
: This displays the last item in the listsafe
: This sets a non-escape valueescape
: This escapes an HTML stringescapejs
: This escapes characters to use in JavaScript stringsdefault
: This defines a default value if the original value equalsNone
orempty
; for example, with{{ value|default:"nothing" }}
, if the value is""
, it will displaynothing
.dictsort
: This sorts the dictionary in the ascending order of the key; for example,{{ value|dictsort:"price"}}
will sort the dictionary byprice
dictsortreversed
: This is used to sort the dictionary in the descending order of the keyfloatformat
: This formats a float value, and the following are the examples:When 45.332
is the value,{{ value|floatformat:2 }}
displays45.33
- When
45.00
is the value,{{ value|floatformat:"-2" }}
displays45
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods:
Conditional statements
This section shows how to execute a conditional statement:
{% if cond %}
: This line checks the condition and discusses the following code when enabled.{% elif cond %}
: This line checks another condition if the first has not been verified. If this condition is satisfied, the following code will be processed.{% else %}
: This line will process the following code if none of the previous conditions have been validated.{% endif %}
: This line ends the processing of conditions.
The following are the different template filters:
addslashes
: This adds slashes before quotescapfirst
: This capitalizes the first characterlower
: This converts the text into lowercaseupper
: This converts the text into uppercasetitle
: This capitalizes all the first characters of each wordcut
: This removes all the values of the argument from the given string, for example,{{ value|cut:"*" }}
removes all the*
characterslinebreaks
: This replaces line breaks in text with the appropriate HTML tagsdate
: This displays a formatted date, for example,{{ value|date:"D d M Y" }}
will displayWed 09 Jan 2008
pluralize
: This allows you to display plurals, shown as follows:You have {{ nb_products }} product{{ nb_products|pluralize }} in our cart. I received {{ nb_diaries }} diar{{ nb_diaries|pluralize:"y,ies" }}.
random
: This returns a random element from the listlinenumbers
: This displays text with line numbers at the left-hand sidefirst
: This displays the first item in the listlast
: This displays the last item in the listsafe
: This sets a non-escape valueescape
: This escapes an HTML stringescapejs
: This escapes characters to use in JavaScript stringsdefault
: This defines a default value if the original value equalsNone
orempty
; for example, with{{ value|default:"nothing" }}
, if the value is""
, it will displaynothing
.dictsort
: This sorts the dictionary in the ascending order of the key; for example,{{ value|dictsort:"price"}}
will sort the dictionary byprice
dictsortreversed
: This is used to sort the dictionary in the descending order of the keyfloatformat
: This formats a float value, and the following are the examples:When 45.332
is the value,{{ value|floatformat:2 }}
displays45.33
- When
45.00
is the value,{{ value|floatformat:"-2" }}
displays45
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods:
The template filters
The following are the different template filters:
addslashes
: This adds slashes before quotescapfirst
: This capitalizes the first characterlower
: This converts the text into lowercaseupper
: This converts the text into uppercasetitle
: This capitalizes all the first characters of each wordcut
: This removes all the values of the argument from the given string, for example,{{ value|cut:"*" }}
removes all the*
characterslinebreaks
: This replaces line breaks in text with the appropriate HTML tagsdate
: This displays a formatted date, for example,{{ value|date:"D d M Y" }}
will displayWed 09 Jan 2008
pluralize
: This allows you to display plurals, shown as follows:You have {{ nb_products }} product{{ nb_products|pluralize }} in our cart. I received {{ nb_diaries }} diar{{ nb_diaries|pluralize:"y,ies" }}.
random
: This returns a random element from the listlinenumbers
: This displays text with line numbers at the left-hand sidefirst
: This displays the first item in the listlast
: This displays the last item in the listsafe
: This sets a non-escape valueescape
: This escapes an HTML stringescapejs
: This escapes characters to use in JavaScript stringsdefault
: This defines a default value if the original value equalsNone
orempty
; for example, with{{ value|default:"nothing" }}
, if the value is""
, it will displaynothing
.dictsort
: This sorts the dictionary in the ascending order of the key; for example,{{ value|dictsort:"price"}}
will sort the dictionary byprice
dictsortreversed
: This is used to sort the dictionary in the descending order of the keyfloatformat
: This formats a float value, and the following are the examples:When 45.332
is the value,{{ value|floatformat:2 }}
displays45.33
- When
45.00
is the value,{{ value|floatformat:"-2" }}
displays45
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods:
The queryset methods
The following are the queryset methods:
all()
: This method retrieves all the records of a model.filter(condition)
: This method allows you to filter a queryset.none()
: This method can return an empty queryset. This method is useful when you want to empty a queryset.dinstinct(field_name)
: This method is used to retrieve the unique values of a field.values_list(field_name)
: This method is used to retrieve the data dictionary of a field.get(condition)
: This method is used to retrieve a record from a model. When using this method, you must be sure that it concerns only one record.exclude(condition)
: This method allows you to exclude some records.
The following elements are the aggregation methods: