В этой статье
- Работа с формами
- Устройство форм в Django
- Работа с формами из кода
- Работа с полями формы
- Доступ к полям формы по именам
- Атрибуты полей формы
- Отображение формы в шаблоне
- Улучшение внешнего вида формы
- Accessing form values: request.POST and cleaned_data.
- Validating form values : is_valid(), validators, clean_() and clean()
- Listing 6-13 Django form is_valid() method for form processing
- Listing 6-14 Django form field validators option with custom validator method for form processing
- Listing 6-15 Django form field validation with clean_() methods
- Listing 6-16. Django form field validation with clean() method
- Listing 6-17. Django form field error assignment with add_error() in clean() method
- Example 2 from wagtail
- Table of Contents
- Full Stack Python
Работа с формами
Возьмём для экспериментов несложную форму.В ней есть два текстовых поля — «Имя» и «Фамилия», и кнопка «Отправить». При нажатии на кнопку браузер отправит данные из формы на страницу, указанную в атрибуте action.
Устройство форм в Django
Чтобы было проще понимать примеры и код, разберём устройство форм на высоком уровне.Форма в Django не обязательно должна работать с моделью: можно создать форму, не связанную с моделью. Поля формы и их типы описывают при создании класса формы; такие классы наследуют от встроенного класса Form.
from django import forms
class ContactForm(forms.Form):
first_name = forms.CharField(label=’Введите имя’, initial=’Лев’)
last_name = forms.CharField(label=’Введите фамилию’, initial=’Толстой’)
Форма может содержать поля разных типов, все они описаны в документации. Когда в шаблоне поле превращается в HTML-код, то применяется виджет, определённый параметром widget. Виджет — это шаблон, по которому генерируется HTML-код поля формы.
Основные типы полей, которые вам будут встречаться:
- BooleanField — соответствует типу bool. Виджет по умолчанию отрисовывает чекбокс ;
- CharField — поле для ввода текста, по умолчанию используется виджет однострочного поля ввода . Виджет можно заменить: если указать в параметрах widget=forms.Textarea, будет отрисовано поле многострочного ввода, <текстареа>;текстареа>
- ChoiceField — поле выбора из выпадающего списка,
- EmailField — однострочное поле ввода текста, но с обязательной проверкой введённой строки на соответствие формату email;
- FileField — поле для отправки файла, в шаблоне отрисует тег . Есть аналогичное поле для отправки только файлов изображений: ImageField;
- IntegerField — поле для ввода чисел: .
Можно самостоятельно создавать новые типы полей и новые виджеты. В Django есть множество готовых виджетов: например, есть виджет для превращения поля ввода в визуальный редактор.
Работа с формами из кода
Запустите в консоли интерактивный режим Django, дальше работать будем в нём: (venv) … $ python manage.py shell
Импортируем модуль forms и создадим класс формы с двумя полями:
>>> from django import forms
>>> class Registration(forms.Form):
… first_name = forms.CharField(label=’Введите имя’, initial=’Лев’)
… last_name = forms.CharField(label=’Введите фамилию’, initial=’Толстой’)
…
>>> form = Registration()
>>> #напечатаем результат, чтобы увидеть HTML-код, который выведет метод as_p()
>>> print(form.as_p())
Сгенерированный HTML-код содержит код полей ввода с необходимыми атрибутами и теги
По умолчанию форма выводится в HTML-таблицу, в элемент
Работа с полями формы
С объектом формы можно работать через цикл for:
>>> for field in form:
… print(field)
…
# поля формы будут напечатаны по очереди
В шаблоне этот же код выглядит так:
{% for field in form %}
{{ field }}
{% endfor %}
Доступ к полям формы по именам
Иногда удобно вывести в шаблон поля формы не циклом, а отдельным кодом.В шаблоне для доступа к полю применяют точечную нотацию: form.field_name.
В Python-коде доступ к полям можно получить, обратившись к объекту form как к словарю, где ключом является имя поля.
>>> print(form[‘first_name’])
Атрибуты полей формы
При выводе формы в шаблон доступны атрибуты объекта field:
- field.label — метка поля, параметр label из описания поля в классе: label=”Введите имя”;
- field.label_tag — этот атрибут даёт доступ к полному тегу label для поля: ;
- field.id_for_label — здесь хранится значение, которое в HTML-теге label указывает, для какого именно поля формы создан этот label. В примере значением тега field.id_for_label будет id_first_name;
- field.value — значение, которое ввёл пользователь;
- field.html_name — атрибут name тега input;
- field.help_text — текст подсказки, который можно передать в коде;
- field.errors — этот атрибут будет заполнен, если при проверке отправленных данных произошла ошибка.
Отображение формы в шаблоне
Осталось
отобразить форму в нашем шаблоне. Перейдем в файл addpage.html и пропишем там
следующие строчки:
Смотрите, мы
самостоятельно прописываем тег
Улучшение внешнего вида формы
Но у нас
названия полей отображаются по-английски и нам бы хотелось их изменить. Для
этого у каждого класса полей формы есть специальный атрибут label, который и
позволяет задавать свои имена, например, так:
class AddPostForm(forms.Form):
title = forms.CharField(max_length=255, label=”Заголовок”)
slug = forms.SlugField(max_length=255, label=”URL”)
content = forms.CharField(widget=forms.Textarea(attrs={‘cols’: 60,’rows’: 10}), label=”Контент”)
is_published = forms.BooleanField(label=”Публикация”)
cat = forms.ModelChoiceField(queryset=Category.objects.all(), label=”Категории”)
Теперь, все
выглядит гораздо приятнее. Давайте для примера сделаем поле content необязательным,
а поле is_published с установленной
галочкой. Соответственно, в классе CharField пропишем
параметр required=False, а в классе BooleanField – параметр initial=True.
Еще в классе ModelChoiceField добавим
параметр empty_label=”Категория не выбрана”, чтобы вместо черточек
отображалась по умолчанию в списке эта фраза.
Со всеми
возможными параметрами можно ознакомиться в документации, все по той же ссылке:
https://djbook.ru/rel3.0/ref/forms/fields.html
Accessing form values: request.POST and cleaned_data.
Once a user fills out a Django
form, the form is sent back to the server to be processed and
perform an action with the user data (e.g. create an order, send an
email, save the data to the database) — a step which is
represented in the POST section in listing 6-8.
One of the key advantages of
Django form processing is you can use the request.POST
variable to create a bound form instance. But although the
request.POST variable is the initial access point to
populate a Django form with user data, you shouldn’t use this data
beyond initializing a form instance, as the data in
request.POST is too raw for direct access.
For example, in
request.POST you still don’t know if the user provided
data is valid. In addition, the data in request.POST
is still treated as strings, so if your Django form happens to have
an IntegerField() or DateField() it still
needs to be converted manually to the expected data type (e.g. ‘6’
to 6 integer, ‘2017-01-01’ to 2017-01-01 datetime), which is just
unnecessary work that another another part of Django forms deals
with.
Once you have a bound form
generated with the request.POST variable, you can then
access each of the form’s field values through the
cleaned_data dictionary. For example, if the bound
form has a form field called name you can use the
syntax form.cleaned_data[‘name’] to access the user
provided name value. More importantly, if the form
field is an IntegerField() named age the
syntax form.cleaned_data[‘age’] produces an integer
value, a formatting behavior that also applies to other form fields
with non-string data types (e.g. DateField()).
Caution You can’t access cleaned_data until
is_valid() is called on the form.
By design, it isn’t possible to
access a form instance’s cleaned_data dictionary
unless you first call the is_valid() method. If you
try to access cleaned_data before calling
is_valid() you’ll get the error AttributeError:
‘form_reference’ object has no attribute ‘cleaned_data’.
If you think about this for a
second it’s good practice, after all, why would you want to access
data that hasn’t been validated ? The next section describes the
is_valid() method.
Validating form values : is_valid(), validators, clean_() and clean()
The is_valid()
method is one of the more important parts of Django form
processing. Once you create a bound form with
request.POST, you call the is_valid()
method on the instance to determine if the included values comply
with a form’s field definitions (e.g. if an
EmailField() value is a valid email). Although the
is_valid() method returns a boolean True
or False value, it has two important side-effects:
- Calling is_valid()
also creates the cleaned_data dictionary on the form
instance to hold the form field values that passed validation
rules. - Calling is_valid() also creates the
errors dictionary on the form instance to hold the
form errors for each of the fields that didn’t pass the validation
rules.
Listing 6-13 illustrates a
modified version of listing 6-8 with the is_valid()
method.
Listing 6-13 Django form is_valid() method for form processing
from django.http import HttpResponseRedirect
def contact(request):
if request.method == ‘POST’:
# POST, generate form with data from the request
form = ContactForm(request.POST)
# Reference is now a bound instance with user data sent in POST
# Call is_valid() to validate data and create cleaned_data and errors dict
if form.is_valid():
# Form data is valid, you can now access validated values in the cleaned_data dict
# e.g. form.cleaned_data[’email’]
# process data, insert into DB, generate email
# Redirect to a new URL
return HttpResponseRedirect(‘/about/contact/thankyou’)
else:
pass # Not needed
# is_valid() method created errors dict, so form reference now contains errors
# this form reference drops to the last return statement where errors
# can then be presented accessing form.errors in a template
else:
# GET, generate blank form
form = ContactForm()
# Reference is now an unbound (empty) form
# Reference form instance (bound/unbound) is sent to template for rendering
return render(request,’about/contact.html’,{‘form’:form})
Notice in listing 6-13 that right
after a bound form instance is created a call is made to the
is_valid() method. If all the form field values comply
against the form field data types, we enter a conditional where
it’s possible to access the form values through the
cleaned_data dictionary, perform whatever business
logic is necessary and relinquish control to another page, which in
listing 6-13 is to perform redirect.
If any of the form field values
fails to pass a rule, then is_valid() returns
False and in the process creates an
errors dictionary with details about the values that
failed to pass their rules. Because of this last automatic creation
of errors, all that’s needed after
is_valid() returns False is to return the
same form instance in order to display the errors
dictionary to an end user so he can correct his mistakes.
But as important as the
is_valid() method is to Django form processing, its
validation is just done against a form field’s data type. For
example, is_valid() can validate if a value is left
empty, if a value matches a given number range or even if a value
is a valid date, in essence anything supported by Django form field
types.
But what if you want to perform
more sophisticated validation after is_valid() ? Like
checking a value against a database before deeming it valid or
checking two values against one another (e.g. a provided zip code
value against a provided city value). While you can add these
validation checks directly after the is_valid() call,
Django offers three more efficient ways to enforce advanced rules
by adding them to the form field or form class definition.
If you want a reusable validation
mechanism you can use across multiple Django form fields, the best
choice is a validator assigned through a form field’s
validators option. The validators form
field option expects a list of methods designed to raise a
forms.ValidationError error in case a value doesn’t
comply with expected rules. Listing 6-14 illustrates a Django form
with one of its fields using a custom validator method via the
validators option.
Listing 6-14 Django form field validators option with custom validator method for form processing
from django import forms
import re
def validate_comment_word_count(value):
count = len(value.split())
if count < 30:
raise forms.ValidationError(('Please provide at least a 30 word message,
%(count)s words is not descriptive enough'), params={'count': count},)class ContactForm(forms.Form):
name = forms.CharField(required=False)
email = forms.EmailField(label='Your email')
comment = forms.CharField(widget=forms.Textarea,validators=[validate_comment_word_count])
The first section in listing 6-14
shows the custom validate_command_word_count()method,
which (rudimentarly) checks if message has at least
thirty words. If the method’s input is not at least thirty words,
Django’s forms.ValidationError error is raised to
indicate a rule violation.
In the bottom half of listing
6-14 you can see a modified ContactForm where the
comment field uses the
validators=[validate_csv] option. This tells Django
that after is_valid() is run and all the form fields
have been checked for errors against their data types, it should
also run the validate_comment_word_count validator
method against the value provided for the comment
field. If the comment value does not comply with this rule, then a
ValidatioError error is raised which is added to the
form errors dictionary — the same one described in
the past section which is used to check field values against their
data types.
As you can see from the example
in listing 6-14, you can equally reuse the custom
validate_comment_word_count() method on any other form
field in the same form or in another Django form through the
validators option. In addition, you can also apply
multiple validators to a field since the validators
option accepts a list of validators. Finally, it’s worth mentioning
the django.core.validators package contains a series
of validators you can also reuse [2] and which are
used behind by the scenes by certain form field data types.
In addition to the form field
validators option, it’s also possible to add
validation form rules through the
clean_
which are created as part of a Django form class — just like
__init__() described earlier. Just like methods
specified in the form field validators option,
clean_
are automatically invoked when the is_valid() method
is run. Listing 6-15 illustrates the use of two
clean_
Listing 6-15 Django form field validation with clean_() methods
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=False)
email = forms.EmailField(label=’Your email’)
comment = forms.CharField(widget=forms.Textarea)
def clean_name(self):
# Get the field value from cleaned_data dict
value = self.cleaned_data[‘name’]
# Check if the value is all upper case
if value.isupper():
# Value is all upper case, raise an error
raise forms.ValidationError(“””Please don’t use all upper
case for your name, use lower case”””,code=’uppercase’)
# Always return value
return value
def clean_email(self):
# Get the field value from cleaned_data dict
value = self.cleaned_data[’email’]
# Check if the value end in @hotmail.com
if value.endswith(‘@hotmail.com’):
# Value ends in @hotmail.com, raise an error
raise forms.ValidationError(“””Please don’t use a hotmail email,
we simply don’t like it”””,code=’hotmail’)
# Always return value
return value
In listing 6-15 there are two
clean_
for the name and email fields. Django
automatically searches for form methods prefixed with
clean_ and attempts to match a form’s field names to
the remaining name, to enforce validation on the field in question.
This means you can have as many clean_
methods as form fields.The logic inside each
clean_
to validators methods. First you extract a field’s
value from the form’s cleaned_data dictionary via the
self reference which represents the form instance.
Next, you run whatever rule or logic you want against the field
value, if you deem the value doesn’t comply you raise a
forms.ValidationError which adds the error to the form
instance. Finally, and this is only different to
validators methods, you must return the field value
irrespective of raising an error or changing its value.Sometimes it’s necessary to apply
a rule that doesn’t necessarily belong to a specific field, in
which case the generic clean() method is the preferred
approach vs. a clean_
6-16 illustrates the use of the clean() method.
Listing 6-16. Django form field validation with clean() method
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=False)
email = forms.EmailField(label=’Your email’)
comment = forms.CharField(widget=forms.Textarea)
def clean(self):
# Call clean() method to ensure base class validation
super(ContactForm, self).clean()
# Get the field values from cleaned_data dict
name = self.cleaned_data.get(‘name’,”)
email = self.cleaned_data.get(’email’,”)
# Check if the name is part of the email
if name.lower() not in email:
# Name is not in email , raise an error
raise forms.ValidationError(“Please provide an email that contains your name, or viceversa”)
In listing 6-16 you can see a
similar approach to the previous clean_
methods in listing 6-15. But because the clean()
method is a class wide method and you’re overriding it yourself, it
differs from clean_
must first explicitly call the clean() method of the
base/parent form class (i.e. super(…).clean()) to
ensure the base class validation is applied. Form field value
extraction is also done through the cleaned_data data
dictionary, as is the validation logic and raising of
forms.ValidationError to indicate a rule violation.
Finally, the clean() method differs from
clean_
return a value.Functionally the
clean() method is different because it’s called after
all the methods in the validators options and
clean_
important because all these methods rely on data in the
cleaned_data dictionary. This means if a
validators or clean_
method raises a ValidationError error it won’t return
any value and the cleaned_data dictionary won’t
contain a value for this field. So by the time the
clean() method is run, the cleaned_data
dictionary may not necessarily have all the form field values if
one was short-circuited in a validators or
clean_
the clean() method uses the safer dictionary access
syntax cleaned_data.get(‘
a default value in case the cleaned_data dictionary
doesn’t have a given field.Another important behavioral
difference between the clean() method,
clean_
methods is how they treat forms.ValidationError. When
a forms.ValidationError is raised in a
validators or clean_
method, the error is assigned to the
question in the form’s errors dictionary — which is
important for display purposes. But when a
forms.ValidationError is raised in the
clean() method, the error is assigned to a special
placeholder field named __all__ — also known as
“non-field errors” — which is also placed in the form’s
errors dictionary.
If you want to assign an error in
the clean() method to a specific form field you can
use the add_error() method as illustrated in listing
6-17.
Listing 6-17. Django form field error assignment with add_error() in clean() method
def clean(self):
# Call clean() method to ensure base class validation
super(ContactForm, self).clean()
# Get the field values from cleaned_data dict
name = self.cleaned_data.get(‘name’,”)
# Check if the name is part of the email
if name.lower() not in email:
# Name is not in email , raise an error
message = “Please provide an email that contains your name, or viceversa”
self.add_error(‘name’, message)
self.add_error(’email’, forms.ValidationError(message))
self.add_error(None, message)
Notice how listing 6-17 uses the
add_error() method on the form instance instead of the
raise forms.ValidationError() syntax. The
add_error() method accepts two arguments, the first
one the form field name on which to assign the error and the second
can be either an error message string or an instance of the
ValidationError class.
The first two
add_error() methods in listing 6-17 assign the error
to the name and email fields,
respectively. And the third add_error() method with
the None key assigns the error to the
__all__ placeholder making it equivalent to
raise forms.ValidationError() from listing 6-16.
Example 2 from wagtail
wagtail
(project website) is a fantastic
Django-based CMS with code that is open source
under the
BSD 3-Clause “New” or “Revised” License.
wagtail / wagtail / admin / messages.py
# messages.py
from django.contrib import messages
from django.core.exceptions import NON_FIELD_ERRORS
from django.template.loader import render_to_string
from django.utils.html import format_html, format_html_join
def render(message, buttons, detail=”):
return render_to_string(‘wagtailadmin/shared/messages.html’, {
‘message’: message,
‘buttons’: buttons,
‘detail’: detail,
})
def debug(request, message, buttons=None, extra_tags=”):
return messages.debug(request, render(message, buttons), extra_tags=extra_tags)
def info(request, message, buttons=None, extra_tags=”):
return messages.info(request, render(message, buttons), extra_tags=extra_tags)
def success(request, message, buttons=None, extra_tags=”):
return messages.success(request, render(message, buttons), extra_tags=extra_tags)
## … source file continues with no further NON_FIELD_ERRORS examples…
Table of Contents
1. Introduction
2. Development Environments
3. Data
4. Web Development
5. Deployment
6. DevOps
Changelog
What Full Stack Means
About the Author
Future Directions
Page Statuses
Django Extensions Django Example Code django.apps.config AppConfig django.conf settings django.conf.urls.url django.contrib.admin django.contrib.admin.filters SimpleListFilter django.contrib.admin.sites register django.contrib.admin helpers django.contrib.admin.helpers ActionForm django.contrib.admin.helpers AdminForm django.contrib.admin.options IS_POPUP_VAR django.contrib.admin.options IncorrectLookupParameters django.contrib.admin.options ModelAdmin django.contrib.admin.options csrf_protect_m django.contrib.admin.sites NotRegistered django.contrib.admin.sites site django.contrib.staticfiles finders django.contrib.staticfiles storage django.contrib.staticfiles.finders BaseFinder django.contrib.staticfiles.finders BaseStorageFinder django.contrib.staticfiles.finders find django.contrib.staticfiles.finders get_finders django.contrib.staticfiles.handlers StaticFilesHandler django.contrib.staticfiles.storage CachedStaticFilesStorage django.contrib.staticfiles.storage HashedFilesMixin django.contrib.staticfiles.storage ManifestStaticFilesStorage django.contrib.staticfiles.storage StaticFilesStorage django.contrib.staticfiles.storage staticfiles_storage django.contrib.staticfiles.utils matches_patterns django.core cache django.core checks django.core exceptions django.core mail django.core management django.core serializers django.core signals django.core signing django.core validators django.core.exceptions DisallowedRedirect django.core.exceptions FieldDoesNotExist django.core.exceptions FieldError django.core.exceptions MiddlewareNotUsed django.core.exceptions NON_FIELD_ERRORS django.core.exceptions ObjectDoesNotExist django.core.exceptions PermissionDenied django.core.exceptions SuspiciousFileOperation django.core.exceptions SuspiciousMultipartForm django.core.exceptions ValidationError django.db DEFAULT_DB_ALIAS django.db DataError django.db DatabaseError django.db IntegrityError django.db ProgrammingError django.db connection django.db connections django.db migrations django.db models django.db router django.db transaction django.db.backends utils django.db.migrations RunPython django.db.migrations.autodetector MigrationAutodetector django.db.migrations.exceptions IrreversibleError django.db.migrations.executor MigrationExecutor django.db.migrations.loader MIGRATIONS_MODULE_NAME django.db.migrations.loader MigrationLoader django.db.migrations.operations.base Operation django.db.migrations.state ProjectState django.db.models.query BaseIterable django.db.models.query EmptyQuerySet django.db.models.query ModelIterable django.db.models.query Prefetch django.db.models.query Q django.db.models.query QuerySet django.db.models.query prefetch_related_objects django.db.models.query_utils DeferredAttribute django.db.models.query_utils PathInfo django.db.models.query_utils Q django.db.models.signals post_delete django.db.models.signals post_save django.db.models.signals pre_delete django.db.models.signals pre_save django.forms BaseForm django.forms CheckboxInput django.forms CheckboxSelectMultiple django.forms DateInput django.forms Field django.forms FileInput django.forms FilePathField django.forms Form django.forms HiddenInput django.forms ImageField django.forms Media django.forms MediaDefiningClass django.forms ModelChoiceField django.forms ModelForm django.forms ModelMultipleChoiceField django.forms MultipleChoiceField django.forms Select django.forms SelectMultiple django.forms ValidationError django.shortcuts get_list_or_404 django.shortcuts get_object_or_404 django.shortcuts redirect django.shortcuts render django.shortcuts resolve_url django.template Context django.template.base Context django.template loader django.template.base FilterExpression django.template.base Node django.template.base NodeList django.template.base Parser django.template.base Template django.template.base TemplateSyntaxError django.template.base TextNode django.template.base Token django.template.base TokenType django.template.base VariableDoesNotExist django.template.base VariableNode django.template.base token_kwargs django.template.context Context django.template.defaultfilters escape django.template.defaultfilters filesizeformat django.template.defaultfilters safe django.template.defaultfilters slugify django.template.defaultfilters striptags django.template.defaultfilters title django.template.defaultfilters truncatechars django.template.loader get_template django.template.loader render_to_string django.template.loader select_template django.template.loader_tags BlockNode django.template.loader_tags ExtendsNode django.template.loader_tags IncludeNode django.template.loaders.filesystem Loader django.urls URLPattern django.urls URLResolver django.urls clear_url_caches django.urls get_callable django.urls get_resolver django.urls get_script_prefix django.urls include django.urls re_path django.urls register_converter django.urls resolve django.urls reverse django.utils dateformat django.utils dateparse django.utils datetime_safe django.utils formats django.utils module_loading django.utils termcolors django.utils translation django.utils tree django.utils.cache add_never_cache_хедерs django.utils.cache cc_delim_re django.utils.cache patch_cache_control django.utils.cache patch_response_хедерs django.utils.cache patch_vary_хедерs django.utils.crypto constant_time_compare django.utils.crypto get_random_string django.utils.datastructures MultiValueDict django.utils.dateparse parse_datetime django.utils.dateparse parse_duration django.utils.dates MONTHS django.utils.datetime_safe datetime django.utils.decorators method_decorator django.utils.deprecation MiddlewareMixin django.utils.deprecation RenameMethodsBase django.utils.duration duration_string django.utils.encoding DjangoUnicodeDecodeError django.utils.encoding filepath_to_uri django.utils.encoding force_bytes django.utils.encoding force_str django.utils.encoding force_text django.utils.encoding iri_to_uri django.utils.encoding is_protected_type django.utils.encoding smart_bytes django.utils.encoding smart_str django.utils.encoding smart_text django.utils.encoding uri_to_iri django.utils.formats get_format django.utils.formats localize_input django.utils.formats sanitize_separators django.utils.functional LazyObject django.utils.functional Promise django.utils.functional SimpleLazyObject django.utils.functional keep_lazy django.utils.functional lazy django.utils.functional total_ordering django.utils.functional wraps django.utils.html conditional_escape django.utils.html escape django.utils.html escapejs django.utils.html format_html_join django.utils.html mark_safe django.utils.html smart_urlquote django.utils.html strip_tags django.utils.http base36_to_int django.utils.http http_date django.utils.http int_to_base36 django.utils.http is_safe_url django.utils.http unquote django.utils.http url_has_allowed_host_and_scheme django.utils.http urlencode django.utils.http urlquote django.utils.http urlunquote django.utils.ipv6 clean_ipv6_address django.utils.itercompat is_iterable django.utils.module_loading autodiscover_modules django.utils.module_loading import_string django.utils.module_loading module_has_submodule django.utils.numberformat format django.utils.safestring SafeData django.utils.safestring SafeText django.utils.safestring mark_safe django.utils.termcolors colorize django.utils.text Truncator django.utils.text capfirst django.utils.text format_lazy django.utils.text get_text_list django.utils.text get_valid_filename django.utils.text slugify django.utils.timezone get_current_timezone django.utils.timezone make_aware django.utils.timezone now django.utils.timezone timedelta django.utils.translation LANGUAGE_SESSION_KEY django.utils.translation activate django.utils.translation deactivate_all django.utils.translation get_language django.utils.translation get_language_from_request django.utils.translation gettext django.utils.translation gettext_lazy django.utils.translation ngettext django.utils.translation override django.utils.translation pgettext django.utils.translation pgettext_lazy django.utils.translation ugettext django.utils.translation ugettext_lazy django.utils.translation ungettext django.utils.translation ungettext_lazy django.utils.version get_complete_version django.views csrf django.views.debug get_default_exception_reporter_filter django.views.decorators.csrf csrf_exempt django.views.decorators.debug sensitive_post_parameters django.views.decorators.http require_GET django.views.decorators.http require_POST django.views.generic CreateView django.views.generic DeleteView django.views.generic DetailView django.views.generic FormView django.views.generic ListView django.views.generic RedirectView django.views.generic TemplateView django.views.generic UpdateView django.views.generic View django.views.generic.base RedirectView django.views.generic.base TemplateResponseMixin django.views.generic.base TemplateView django.views.generic.base View django.views.generic.detail SingleObjectMixin django.views.generic.edit CreateView django.views.generic.edit DeleteView django.views.generic.edit DeletionMixin django.views.generic.edit FormMixin django.views.generic.edit FormView django.views.generic.list ListView django.views.generic.list MultipleObjectMixin django.views.i18n JavaScriptCatalog django.views.static serve django.views.static was_modified_since django.contrib.auth.decorators login_required django.contrib.auth get_user_model django.contrib.auth.hashers make_password django.core.exceptions ImproperlyConfigured django.core.mail.messages EmailMessage django.core.mail.send_mail django.core.management.base BaseCommand django.db.models AutoField django.db.models BooleanField django.db.models CharField django.db.models DateField django.db.models DateTimeField django.db.models FileField django.db.models ForeignKey django.db.models GenericIPAddressField django.db.models ImageField django.db.models IntegerField django.db.models Model django.db.models PositiveIntegerField django.db.models PositiveSmallIntegerField django.db.models.signal django.db.models SlugField django.db.models SmallIntegerField django.db.models TextField django.db OperationalError django.dispatch Signal django.forms django.forms BooleanField django.forms CharField django.forms ChoiceField django.forms DateField django.forms DateTimeField django.forms EmailField django.forms IntegerField django.forms TypedChoiceField django.http Http404 django.http HttpResponse django.http HttpResponseBadRequest django.http HttpResponseForbidden django.http HttpResponseNotModified django.http HttpResponsePermanentRedirect django.http HttpResponseRedirect django.template.response SimpleTemplateResponse django.template.response TemplateResponse django.urls.path django.urls reverse_lazy django.urls.exceptions NoReverseMatch django.urls.exceptions Resolver404 django.utils.html format_html django.utils.timezone …or view the full table of contents.
Full Stack Python
Full Stack Python
is an open book that explains concepts in plain language and provides
helpful resources for those topics.
Updates via
Twitter &
Facebook.
- https://mob25.com/django-dorabotka-shablona-formy-registracii/
- https://proproprogs.ru/django/ispolzovanie-form-ne-svyazannyh-s-modelyami
- https://www.webforefront.com/django/formprocessing.html
- https://www.fullstackpython.com/django-core-exceptions-non-field-errors-examples.html