final touches, paypal button, spelling errors, donate & twitter links, etc
This commit is contained in:
1 parent
c31f739395
commit
4d688cab5e
4698 files changed
+67509
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
[Dolphin]
|
||||||
|
Timestamp=2022,6,11,16,22,58.307
|
||||||
|
Version=4
|
||||||
|
VisibleRoles=Icons_text,Icons_modificationtime,Icons_size
|
||||||
|
|
||||||
|
[Settings]
|
||||||
|
HiddenFilesShown=true
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018-present Justin Mayer
|
||||||
|
# Copyright (c) 2008—2016 Andy Mikhailenko
|
||||||
|
#
|
||||||
|
# This file is part of django-autoslug.
|
||||||
|
#
|
||||||
|
# django-autoslug is free software under terms of the GNU Lesser
|
||||||
|
# General Public License version 3 (LGPLv3) as published by the Free
|
||||||
|
# Software Foundation. See the file README for copying conditions.
|
||||||
|
#
|
||||||
|
from autoslug.fields import AutoSlugField
|
||||||
|
|
||||||
|
|
||||||
|
__version__ = '1.9.8'
|
||||||
|
__all__ = ['AutoSlugField']
|
||||||
@@ -0,0 +1,354 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018-present Justin Mayer
|
||||||
|
# Copyright (c) 2008—2016 Andy Mikhailenko
|
||||||
|
#
|
||||||
|
# This file is part of django-autoslug.
|
||||||
|
#
|
||||||
|
# django-autoslug is free software under terms of the GNU Lesser
|
||||||
|
# General Public License version 3 (LGPLv3) as published by the Free
|
||||||
|
# Software Foundation. See the file README for copying conditions.
|
||||||
|
#
|
||||||
|
|
||||||
|
# django
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db.models.fields import SlugField
|
||||||
|
from django.db.models.signals import post_save
|
||||||
|
|
||||||
|
# 3rd-party
|
||||||
|
try:
|
||||||
|
from south.modelsinspector import introspector
|
||||||
|
except ImportError:
|
||||||
|
introspector = lambda self: [], {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
from modeltranslation import utils as modeltranslation_utils
|
||||||
|
except ImportError:
|
||||||
|
modeltranslation_utils = None
|
||||||
|
|
||||||
|
# this app
|
||||||
|
from autoslug.settings import slugify, autoslug_modeltranslation_enable
|
||||||
|
from autoslug import utils
|
||||||
|
|
||||||
|
__all__ = ['AutoSlugField']
|
||||||
|
|
||||||
|
SLUG_INDEX_SEPARATOR = '-' # the "-" in "foo-2"
|
||||||
|
|
||||||
|
try: # pragma: nocover
|
||||||
|
# Python 2.x
|
||||||
|
basestring
|
||||||
|
except NameError: # pragma: nocover
|
||||||
|
# Python 3.x
|
||||||
|
basestring = str
|
||||||
|
|
||||||
|
|
||||||
|
class AutoSlugField(SlugField):
|
||||||
|
"""
|
||||||
|
AutoSlugField is an extended SlugField able to automatically resolve name
|
||||||
|
clashes.
|
||||||
|
|
||||||
|
AutoSlugField can also perform the following tasks on save:
|
||||||
|
|
||||||
|
- populate itself from another field (using `populate_from`),
|
||||||
|
- use custom `slugify` function (using `slugify` or :doc:`settings`), and
|
||||||
|
- preserve uniqueness of the value (using `unique` or `unique_with`).
|
||||||
|
|
||||||
|
None of the tasks is mandatory, i.e. you can have auto-populated non-unique
|
||||||
|
fields, manually entered unique ones (absolutely unique or within a given
|
||||||
|
date) or both.
|
||||||
|
|
||||||
|
Uniqueness is preserved by checking if the slug is unique with given constraints
|
||||||
|
(`unique_with`) or globally (`unique`) and adding a number to the slug to make
|
||||||
|
it unique.
|
||||||
|
|
||||||
|
:param always_update: boolean: if True, the slug is updated each time the
|
||||||
|
model instance is saved. Use with care because `cool URIs don't
|
||||||
|
change`_ (and the slug is usually a part of object's URI). Note that
|
||||||
|
even if the field is editable, any manual changes will be lost when
|
||||||
|
this option is activated.
|
||||||
|
:param populate_from: string or callable: if string is given, it is considered
|
||||||
|
as the name of attribute from which to fill the slug. If callable is given,
|
||||||
|
it should accept `instance` parameter and return a value to fill the slug
|
||||||
|
with.
|
||||||
|
:param sep: string: if defined, overrides default separator for automatically
|
||||||
|
incremented slug index (i.e. the "-" in "foo-2").
|
||||||
|
:param slugify: callable: if defined, overrides `AUTOSLUG_SLUGIFY_FUNCTION`
|
||||||
|
defined in :doc:`settings`.
|
||||||
|
:param unique: boolean: ensure total slug uniqueness (unless more precise
|
||||||
|
`unique_with` is defined).
|
||||||
|
:param unique_with: string or tuple of strings: name or names of attributes
|
||||||
|
to check for "partial uniqueness", i.e. there will not be two objects
|
||||||
|
with identical slugs if these objects share the same values of given
|
||||||
|
attributes. For instance, ``unique_with='pub_date'`` tells AutoSlugField
|
||||||
|
to enforce slug uniqueness of all items published on given date. The
|
||||||
|
slug, however, may reappear on another date. If more than one field is
|
||||||
|
given, e.g. ``unique_with=('pub_date', 'author')``, then the same slug may
|
||||||
|
reappear within a day or within some author's articles but never within
|
||||||
|
a day for the same author. Foreign keys are also supported, i.e. not only
|
||||||
|
`unique_with='author'` will do, but also `unique_with='author__name'`.
|
||||||
|
|
||||||
|
.. _cool URIs don't change: http://w3.org/Provider/Style/URI.html
|
||||||
|
|
||||||
|
.. note:: always place any slug attribute *after* attributes referenced
|
||||||
|
by it (i.e. those from which you wish to `populate_from` or check
|
||||||
|
`unique_with`). The reasoning is that autosaved dates and other such
|
||||||
|
fields must be already processed before using them in the AutoSlugField.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from autoslug import AutoSlugField
|
||||||
|
|
||||||
|
class Article(models.Model):
|
||||||
|
'''An article with title, date and slug. The slug is not totally
|
||||||
|
unique but there will be no two articles with the same slug within
|
||||||
|
any month.
|
||||||
|
'''
|
||||||
|
title = models.CharField(max_length=200)
|
||||||
|
pub_date = models.DateField(auto_now_add=True)
|
||||||
|
slug = AutoSlugField(populate_from='title', unique_with='pub_date__month')
|
||||||
|
|
||||||
|
|
||||||
|
More options:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
# slugify but allow non-unique slugs
|
||||||
|
slug = AutoSlugField()
|
||||||
|
|
||||||
|
# globally unique, silently fix on conflict ("foo" --> "foo-1".."foo-n")
|
||||||
|
slug = AutoSlugField(unique=True)
|
||||||
|
|
||||||
|
# autoslugify value from attribute named "title"; editable defaults to False
|
||||||
|
slug = AutoSlugField(populate_from='title')
|
||||||
|
|
||||||
|
# same as above but force editable=True
|
||||||
|
slug = AutoSlugField(populate_from='title', editable=True)
|
||||||
|
|
||||||
|
# ensure that slug is unique with given date (not globally)
|
||||||
|
slug = AutoSlugField(unique_with='pub_date')
|
||||||
|
|
||||||
|
# ensure that slug is unique with given date AND category
|
||||||
|
slug = AutoSlugField(unique_with=('pub_date','category'))
|
||||||
|
|
||||||
|
# ensure that slug is unique with an external object
|
||||||
|
# assuming that author=ForeignKey(Author)
|
||||||
|
slug = AutoSlugField(unique_with='author')
|
||||||
|
|
||||||
|
# ensure that slug is unique with a subset of external objects (by lookups)
|
||||||
|
# assuming that author=ForeignKey(Author)
|
||||||
|
slug = AutoSlugField(unique_with='author__name')
|
||||||
|
|
||||||
|
# mix above-mentioned behaviour bits
|
||||||
|
slug = AutoSlugField(populate_from='title', unique_with='pub_date')
|
||||||
|
|
||||||
|
# minimum date granularity is shifted from day to month
|
||||||
|
slug = AutoSlugField(populate_from='title', unique_with='pub_date__month')
|
||||||
|
|
||||||
|
# autoslugify value from a dynamic attribute (i.e. a method)
|
||||||
|
slug = AutoSlugField(populate_from='get_full_name')
|
||||||
|
|
||||||
|
# autoslugify value from a custom callable
|
||||||
|
# (ex. usage: user profile models)
|
||||||
|
slug = AutoSlugField(populate_from=lambda instance: instance.user.get_full_name())
|
||||||
|
|
||||||
|
# specify model manager for looking up slugs shared by subclasses
|
||||||
|
|
||||||
|
class Article(models.Model):
|
||||||
|
'''An article with title, date and slug. The slug is not totally
|
||||||
|
unique but there will be no two articles with the same slug within
|
||||||
|
any month.
|
||||||
|
'''
|
||||||
|
objects = models.Manager()
|
||||||
|
title = models.CharField(max_length=200)
|
||||||
|
slug = AutoSlugField(populate_from='title', unique_with='pub_date__month', manager=objects)
|
||||||
|
|
||||||
|
class NewsArticle(Article):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# autoslugify value using custom `slugify` function
|
||||||
|
from autoslug.settings import slugify as default_slugify
|
||||||
|
def custom_slugify(value):
|
||||||
|
return default_slugify(value).replace('-', '_')
|
||||||
|
slug = AutoSlugField(slugify=custom_slugify)
|
||||||
|
|
||||||
|
"""
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
kwargs['max_length'] = kwargs.get('max_length', 50)
|
||||||
|
|
||||||
|
# autopopulated slug is not editable unless told so
|
||||||
|
self.populate_from = kwargs.pop('populate_from', None)
|
||||||
|
if self.populate_from:
|
||||||
|
kwargs.setdefault('editable', False)
|
||||||
|
|
||||||
|
# unique_with value can be string or tuple
|
||||||
|
self.unique_with = kwargs.pop('unique_with', ())
|
||||||
|
if isinstance(self.unique_with, basestring):
|
||||||
|
self.unique_with = (self.unique_with,)
|
||||||
|
|
||||||
|
self.slugify = kwargs.pop('slugify', slugify)
|
||||||
|
assert hasattr(self.slugify, '__call__')
|
||||||
|
|
||||||
|
self.index_sep = kwargs.pop('sep', SLUG_INDEX_SEPARATOR)
|
||||||
|
|
||||||
|
if self.unique_with:
|
||||||
|
# we will do "manual" granular check below
|
||||||
|
kwargs['unique'] = False
|
||||||
|
|
||||||
|
# Set db_index=True unless it's been set manually.
|
||||||
|
if 'db_index' not in kwargs:
|
||||||
|
kwargs['db_index'] = True
|
||||||
|
|
||||||
|
# A boolean instructing the field to accept Unicode letters in
|
||||||
|
# addition to ASCII letters. Defaults to False.
|
||||||
|
self.allow_unicode = kwargs.pop('allow_unicode', False)
|
||||||
|
|
||||||
|
# When using model inheritence, set manager to search for matching
|
||||||
|
# slug values
|
||||||
|
self.manager = kwargs.pop('manager', None)
|
||||||
|
self.manager_name = kwargs.pop('manager_name', None)
|
||||||
|
|
||||||
|
self.always_update = kwargs.pop('always_update', False)
|
||||||
|
super(SlugField, self).__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
def deconstruct(self):
|
||||||
|
name, path, args, kwargs = super(AutoSlugField, self).deconstruct()
|
||||||
|
|
||||||
|
if self.max_length == 50:
|
||||||
|
kwargs.pop('max_length', None)
|
||||||
|
|
||||||
|
if self.populate_from is not None:
|
||||||
|
kwargs['populate_from'] = self.populate_from
|
||||||
|
if self.editable is not False:
|
||||||
|
kwargs['editable'] = self.editable
|
||||||
|
|
||||||
|
if self.unique_with != ():
|
||||||
|
kwargs['unique_with'] = self.unique_with
|
||||||
|
kwargs.pop('unique', None)
|
||||||
|
|
||||||
|
if self.slugify != slugify:
|
||||||
|
kwargs['slugify'] = self.slugify
|
||||||
|
|
||||||
|
if self.index_sep != SLUG_INDEX_SEPARATOR:
|
||||||
|
kwargs['sep'] = self.index_sep
|
||||||
|
|
||||||
|
kwargs.pop('db_index', None)
|
||||||
|
|
||||||
|
if self.manager is not None:
|
||||||
|
kwargs['manager'] = self.manager
|
||||||
|
|
||||||
|
if self.manager_name is not None:
|
||||||
|
kwargs['manager_name'] = self.manager_name
|
||||||
|
|
||||||
|
if self.always_update:
|
||||||
|
kwargs['always_update'] = self.always_update
|
||||||
|
|
||||||
|
if 'manager' in kwargs:
|
||||||
|
del kwargs['manager']
|
||||||
|
|
||||||
|
return name, path, args, kwargs
|
||||||
|
|
||||||
|
def pre_save(self, instance, add):
|
||||||
|
|
||||||
|
# get currently entered slug
|
||||||
|
value = self.value_from_object(instance)
|
||||||
|
|
||||||
|
if self.manager is not None:
|
||||||
|
manager = self.manager
|
||||||
|
elif self.manager_name is not None:
|
||||||
|
manager = getattr(self.model, self.manager_name)
|
||||||
|
else:
|
||||||
|
manager = None
|
||||||
|
|
||||||
|
# autopopulate
|
||||||
|
if self.always_update or (self.populate_from and not value):
|
||||||
|
value = utils.get_prepopulated_value(self, instance)
|
||||||
|
|
||||||
|
# pragma: nocover
|
||||||
|
if __debug__ and not value and not self.blank:
|
||||||
|
print('Failed to populate slug %s.%s from %s' % \
|
||||||
|
(instance._meta.object_name, self.name, self.populate_from))
|
||||||
|
|
||||||
|
slug = None
|
||||||
|
if value:
|
||||||
|
slug = self.slugify(value)
|
||||||
|
if not slug:
|
||||||
|
slug = None
|
||||||
|
|
||||||
|
if not self.blank:
|
||||||
|
slug = instance._meta.model_name
|
||||||
|
elif not self.null:
|
||||||
|
slug = ''
|
||||||
|
|
||||||
|
if slug:
|
||||||
|
slug = utils.crop_slug(self, slug)
|
||||||
|
|
||||||
|
# ensure the slug is unique (if required)
|
||||||
|
if self.unique or self.unique_with:
|
||||||
|
slug = utils.generate_unique_slug(self, instance, slug, manager)
|
||||||
|
|
||||||
|
assert slug, 'value is filled before saving'
|
||||||
|
|
||||||
|
# make the updated slug available as instance attribute
|
||||||
|
setattr(instance, self.name, slug)
|
||||||
|
|
||||||
|
# modeltranslation support
|
||||||
|
if 'modeltranslation' in settings.INSTALLED_APPS \
|
||||||
|
and not hasattr(self.populate_from, '__call__') \
|
||||||
|
and autoslug_modeltranslation_enable:
|
||||||
|
post_save.connect(modeltranslation_update_slugs, sender=type(instance))
|
||||||
|
|
||||||
|
return slug
|
||||||
|
|
||||||
|
|
||||||
|
def south_field_triple(self):
|
||||||
|
"Returns a suitable description of this field for South."
|
||||||
|
args, kwargs = introspector(self)
|
||||||
|
kwargs.update({
|
||||||
|
'populate_from': 'None' if callable(self.populate_from) else repr(self.populate_from),
|
||||||
|
'unique_with': repr(self.unique_with)
|
||||||
|
})
|
||||||
|
return ('autoslug.fields.AutoSlugField', args, kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def modeltranslation_update_slugs(sender, **kwargs):
|
||||||
|
# https://bitbucket.org/neithere/django-autoslug/pull-request/11/modeltranslation-support-fix-issue-19/
|
||||||
|
# http://django-modeltranslation.readthedocs.org
|
||||||
|
#
|
||||||
|
# TODO: tests
|
||||||
|
#
|
||||||
|
if not modeltranslation_utils:
|
||||||
|
return
|
||||||
|
|
||||||
|
instance = kwargs['instance']
|
||||||
|
slugs = {}
|
||||||
|
|
||||||
|
for field in instance._meta.fields:
|
||||||
|
if type(field) != AutoSlugField:
|
||||||
|
continue
|
||||||
|
if not field.populate_from:
|
||||||
|
continue
|
||||||
|
for lang in settings.LANGUAGES:
|
||||||
|
lang_code, _ = lang
|
||||||
|
lang_code = lang_code.replace('-', '_')
|
||||||
|
|
||||||
|
populate_from_localized = modeltranslation_utils.build_localized_fieldname(field.populate_from, lang_code)
|
||||||
|
field_name_localized = modeltranslation_utils.build_localized_fieldname(field.name, lang_code)
|
||||||
|
|
||||||
|
# The source field or the slug field itself may not be registered
|
||||||
|
# with translator
|
||||||
|
if not hasattr(instance, populate_from_localized):
|
||||||
|
continue
|
||||||
|
if not hasattr(instance, field_name_localized):
|
||||||
|
continue
|
||||||
|
|
||||||
|
populate_from_value = getattr(instance, populate_from_localized)
|
||||||
|
field_value = getattr(instance, field_name_localized)
|
||||||
|
|
||||||
|
if not field_value or field.always_update:
|
||||||
|
slug = field.slugify(populate_from_value)
|
||||||
|
slugs[field_name_localized] = slug
|
||||||
|
|
||||||
|
sender.objects.filter(pk=instance.pk).update(**slugs)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,74 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018-present Justin Mayer
|
||||||
|
# Copyright (c) 2008—2016 Andy Mikhailenko
|
||||||
|
#
|
||||||
|
# This file is part of django-autoslug.
|
||||||
|
#
|
||||||
|
# django-autoslug is free software under terms of the GNU Lesser
|
||||||
|
# General Public License version 3 (LGPLv3) as published by the Free
|
||||||
|
# Software Foundation. See the file README for copying conditions.
|
||||||
|
#
|
||||||
|
"""
|
||||||
|
Django settings that affect django-autoslug:
|
||||||
|
|
||||||
|
`AUTOSLUG_SLUGIFY_FUNCTION`
|
||||||
|
Allows to define a custom slugifying function.
|
||||||
|
|
||||||
|
The function can be repsesented as string or callable, e.g.::
|
||||||
|
|
||||||
|
# custom function, path as string:
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = 'some_app.slugify_func'
|
||||||
|
|
||||||
|
# custom function, callable:
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = some_app.slugify_func
|
||||||
|
|
||||||
|
# custom function, defined inline:
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = lambda slug: 'can i haz %s?' % slug
|
||||||
|
|
||||||
|
If no value is given, default value is used.
|
||||||
|
|
||||||
|
Default value is one of these depending on availability in given order:
|
||||||
|
|
||||||
|
* `unidecode.unidecode()` if Unidecode_ is available;
|
||||||
|
* `pytils.translit.slugify()` if pytils_ is available;
|
||||||
|
* `django.template.defaultfilters.slugify()` bundled with Django.
|
||||||
|
|
||||||
|
django-autoslug also ships a couple of slugify functions that use
|
||||||
|
the translitcodec_ Python library, e.g.::
|
||||||
|
|
||||||
|
# using as many characters as needed to make a natural replacement
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_long'
|
||||||
|
|
||||||
|
# using the minimum number of characters to make a replacement
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_short'
|
||||||
|
|
||||||
|
# only performing single character replacements
|
||||||
|
AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_one'
|
||||||
|
|
||||||
|
.. _Unidecode: http://pypi.python.org/pypi/Unidecode
|
||||||
|
.. _pytils: http://pypi.python.org/pypi/pytils
|
||||||
|
.. _translitcodec: http://pypi.python.org/pypi/translitcodec
|
||||||
|
|
||||||
|
`AUTOSLUG_MODELTRANSLATION_ENABLE`
|
||||||
|
Django-autoslug support of modeltranslation_ is still experimental.
|
||||||
|
If you wish to enable it, please set this option to `True` in your project
|
||||||
|
settings. Default is `False`.
|
||||||
|
|
||||||
|
.. _modeltranslation: http://django-modeltranslation.readthedocs.org
|
||||||
|
|
||||||
|
"""
|
||||||
|
from django.conf import settings
|
||||||
|
from django import VERSION
|
||||||
|
|
||||||
|
if VERSION >= (2, 0):
|
||||||
|
from django.urls import get_callable
|
||||||
|
else:
|
||||||
|
from django.core.urlresolvers import get_callable
|
||||||
|
|
||||||
|
# use custom slugifying function if any
|
||||||
|
slugify_function_path = getattr(settings, 'AUTOSLUG_SLUGIFY_FUNCTION', 'autoslug.utils.slugify')
|
||||||
|
slugify = get_callable(slugify_function_path)
|
||||||
|
|
||||||
|
# enable/disable modeltranslation support
|
||||||
|
autoslug_modeltranslation_enable = getattr(settings, 'AUTOSLUG_MODELTRANSLATION_ENABLE', False)
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018-present Justin Mayer
|
||||||
|
# Copyright (c) 2008—2016 Andy Mikhailenko
|
||||||
|
#
|
||||||
|
# This file is part of django-autoslug.
|
||||||
|
#
|
||||||
|
# django-autoslug is free software under terms of the GNU Lesser
|
||||||
|
# General Public License version 3 (LGPLv3) as published by the Free
|
||||||
|
# Software Foundation. See the file README for copying conditions.
|
||||||
|
#
|
||||||
|
|
||||||
|
# django
|
||||||
|
import datetime
|
||||||
|
from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist
|
||||||
|
from django.db.models import ForeignKey
|
||||||
|
from django.db.models.fields import DateField
|
||||||
|
from django.template.defaultfilters import slugify as django_slugify
|
||||||
|
from django.utils.timezone import localtime, is_aware
|
||||||
|
|
||||||
|
try:
|
||||||
|
# i18n-friendly approach
|
||||||
|
from unidecode import unidecode
|
||||||
|
except ImportError:
|
||||||
|
try:
|
||||||
|
# Cyrillic transliteration (primarily Russian)
|
||||||
|
from pytils.translit import slugify
|
||||||
|
except ImportError:
|
||||||
|
# fall back to Django's default method
|
||||||
|
slugify = django_slugify
|
||||||
|
else:
|
||||||
|
# Use Django's default method over decoded string
|
||||||
|
def slugify(value):
|
||||||
|
return django_slugify(unidecode(value))
|
||||||
|
|
||||||
|
|
||||||
|
def get_prepopulated_value(field, instance):
|
||||||
|
"""
|
||||||
|
Returns preliminary value based on `populate_from`.
|
||||||
|
"""
|
||||||
|
if hasattr(field.populate_from, '__call__'):
|
||||||
|
# AutoSlugField(populate_from=lambda instance: ...)
|
||||||
|
return field.populate_from(instance)
|
||||||
|
else:
|
||||||
|
# AutoSlugField(populate_from='foo')
|
||||||
|
attr = getattr(instance, field.populate_from)
|
||||||
|
return callable(attr) and attr() or attr
|
||||||
|
|
||||||
|
|
||||||
|
def generate_unique_slug(field, instance, slug, manager):
|
||||||
|
"""
|
||||||
|
Generates unique slug by adding a number to given value until no model
|
||||||
|
instance can be found with such slug. If ``unique_with`` (a tuple of field
|
||||||
|
names) was specified for the field, all these fields are included together
|
||||||
|
in the query when looking for a "rival" model instance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
original_slug = slug = crop_slug(field, slug)
|
||||||
|
|
||||||
|
default_lookups = tuple(get_uniqueness_lookups(field, instance, field.unique_with))
|
||||||
|
|
||||||
|
index = 1
|
||||||
|
|
||||||
|
if not manager:
|
||||||
|
manager = field.model._default_manager
|
||||||
|
|
||||||
|
|
||||||
|
# keep changing the slug until it is unique
|
||||||
|
while True:
|
||||||
|
# find instances with same slug
|
||||||
|
lookups = dict(default_lookups, **{field.name: slug})
|
||||||
|
rivals = manager.filter(**lookups)
|
||||||
|
if instance.pk:
|
||||||
|
rivals = rivals.exclude(pk=instance.pk)
|
||||||
|
|
||||||
|
if not rivals:
|
||||||
|
# the slug is unique, no model uses it
|
||||||
|
return slug
|
||||||
|
|
||||||
|
# the slug is not unique; change once more
|
||||||
|
index += 1
|
||||||
|
|
||||||
|
# ensure the resulting string is not too long
|
||||||
|
tail_length = len(field.index_sep) + len(str(index))
|
||||||
|
combined_length = len(original_slug) + tail_length
|
||||||
|
if field.max_length < combined_length:
|
||||||
|
original_slug = original_slug[:field.max_length - tail_length]
|
||||||
|
|
||||||
|
# re-generate the slug
|
||||||
|
data = dict(slug=original_slug, sep=field.index_sep, index=index)
|
||||||
|
slug = '%(slug)s%(sep)s%(index)d' % data
|
||||||
|
|
||||||
|
# ...next iteration...
|
||||||
|
|
||||||
|
|
||||||
|
def get_uniqueness_lookups(field, instance, unique_with):
|
||||||
|
"""
|
||||||
|
Returns a dict'able tuple of lookups to ensure uniqueness of a slug.
|
||||||
|
"""
|
||||||
|
for original_lookup_name in unique_with:
|
||||||
|
if '__' in original_lookup_name:
|
||||||
|
field_name, inner_lookup = original_lookup_name.split('__', 1)
|
||||||
|
else:
|
||||||
|
field_name, inner_lookup = original_lookup_name, None
|
||||||
|
|
||||||
|
try:
|
||||||
|
other_field = instance._meta.get_field(field_name)
|
||||||
|
except FieldDoesNotExist:
|
||||||
|
raise ValueError('Could not find attribute %s.%s referenced'
|
||||||
|
' by %s.%s (see constraint `unique_with`)'
|
||||||
|
% (instance._meta.object_name, field_name,
|
||||||
|
instance._meta.object_name, field.name))
|
||||||
|
|
||||||
|
if field == other_field:
|
||||||
|
raise ValueError('Attribute %s.%s references itself in `unique_with`.'
|
||||||
|
' Please use "unique=True" for this case.'
|
||||||
|
% (instance._meta.object_name, field_name))
|
||||||
|
|
||||||
|
value = getattr(instance, field_name)
|
||||||
|
if not value:
|
||||||
|
if other_field.blank:
|
||||||
|
field_object = instance._meta.get_field(field_name)
|
||||||
|
if isinstance(field_object, ForeignKey):
|
||||||
|
lookup = '%s__isnull' % field_name
|
||||||
|
yield lookup, True
|
||||||
|
break
|
||||||
|
raise ValueError('Could not check uniqueness of %s.%s with'
|
||||||
|
' respect to %s.%s because the latter is empty.'
|
||||||
|
' Please ensure that "%s" is declared *after*'
|
||||||
|
' all fields listed in unique_with.'
|
||||||
|
% (instance._meta.object_name, field.name,
|
||||||
|
instance._meta.object_name, field_name,
|
||||||
|
field.name))
|
||||||
|
if isinstance(value, datetime.datetime) and is_aware(value):
|
||||||
|
value = localtime(value)
|
||||||
|
if isinstance(other_field, DateField): # DateTimeField is a DateField subclass
|
||||||
|
inner_lookup = inner_lookup or 'day'
|
||||||
|
|
||||||
|
if '__' in inner_lookup:
|
||||||
|
raise ValueError('The `unique_with` constraint in %s.%s'
|
||||||
|
' is set to "%s", but AutoSlugField only'
|
||||||
|
' accepts one level of nesting for dates'
|
||||||
|
' (e.g. "date__month").'
|
||||||
|
% (instance._meta.object_name, field.name,
|
||||||
|
original_lookup_name))
|
||||||
|
|
||||||
|
parts = ['year', 'month', 'day']
|
||||||
|
try:
|
||||||
|
granularity = parts.index(inner_lookup) + 1
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError('expected one of %s, got "%s" in "%s"'
|
||||||
|
% (parts, inner_lookup, original_lookup_name))
|
||||||
|
else:
|
||||||
|
for part in parts[:granularity]:
|
||||||
|
lookup = '%s__%s' % (field_name, part)
|
||||||
|
yield lookup, getattr(value, part)
|
||||||
|
else:
|
||||||
|
# TODO: this part should be documented as it involves recursion
|
||||||
|
if inner_lookup:
|
||||||
|
if not hasattr(value, '_meta'):
|
||||||
|
raise ValueError('Could not resolve lookup "%s" in `unique_with` of %s.%s'
|
||||||
|
% (original_lookup_name, instance._meta.object_name, field.name))
|
||||||
|
for inner_name, inner_value in get_uniqueness_lookups(field, value, [inner_lookup]):
|
||||||
|
yield original_lookup_name, inner_value
|
||||||
|
else:
|
||||||
|
yield field_name, value
|
||||||
|
|
||||||
|
|
||||||
|
def crop_slug(field, slug):
|
||||||
|
if field.max_length < len(slug):
|
||||||
|
return slug[:field.max_length]
|
||||||
|
return slug
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
import translitcodec
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
import re
|
||||||
|
PUNCT_RE = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
|
||||||
|
|
||||||
|
def translitcodec_slugify(codec):
|
||||||
|
def _slugify(value, delim='-', encoding=''):
|
||||||
|
"""
|
||||||
|
Generates an ASCII-only slug.
|
||||||
|
|
||||||
|
Borrowed from http://flask.pocoo.org/snippets/5/
|
||||||
|
"""
|
||||||
|
if encoding:
|
||||||
|
encoder = "%s/%s" % (codec, encoding)
|
||||||
|
else:
|
||||||
|
encoder = codec
|
||||||
|
result = []
|
||||||
|
for word in PUNCT_RE.split(value.lower()):
|
||||||
|
word = word.encode(encoder)
|
||||||
|
if word:
|
||||||
|
result.append(word)
|
||||||
|
return unicode(delim.join(result))
|
||||||
|
return _slugify
|
||||||
|
|
||||||
|
translit_long = translitcodec_slugify("translit/long")
|
||||||
|
translit_short = translitcodec_slugify("translit/short")
|
||||||
|
translit_one = translitcodec_slugify("translit/one")
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
VERSION = (6, 4, 2)
|
||||||
|
__version__ = ".".join(map(str, VERSION))
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
DEFAULT_CONFIG = {
|
||||||
|
"skin": "moono-lisa",
|
||||||
|
"toolbar_Basic": [["Source", "-", "Bold", "Italic"]],
|
||||||
|
"toolbar_Full": [
|
||||||
|
[
|
||||||
|
"Styles",
|
||||||
|
"Format",
|
||||||
|
"Bold",
|
||||||
|
"Italic",
|
||||||
|
"Underline",
|
||||||
|
"Strike",
|
||||||
|
"SpellChecker",
|
||||||
|
"Undo",
|
||||||
|
"Redo",
|
||||||
|
],
|
||||||
|
["Link", "Unlink", "Anchor"],
|
||||||
|
["Image", "Flash", "Table", "HorizontalRule"],
|
||||||
|
["TextColor", "BGColor"],
|
||||||
|
["Smiley", "SpecialChar"],
|
||||||
|
["Source"],
|
||||||
|
],
|
||||||
|
"toolbar": "Full",
|
||||||
|
"height": 291,
|
||||||
|
"width": 835,
|
||||||
|
"filebrowserWindowWidth": 940,
|
||||||
|
"filebrowserWindowHeight": 725,
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from django import forms
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
from .widgets import CKEditorWidget
|
||||||
|
|
||||||
|
|
||||||
|
class RichTextField(models.TextField):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.config_name = kwargs.pop("config_name", "default")
|
||||||
|
self.extra_plugins = kwargs.pop("extra_plugins", [])
|
||||||
|
self.external_plugin_resources = kwargs.pop("external_plugin_resources", [])
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
def formfield(self, **kwargs):
|
||||||
|
defaults = {
|
||||||
|
"form_class": RichTextFormField,
|
||||||
|
"config_name": self.config_name,
|
||||||
|
"extra_plugins": self.extra_plugins,
|
||||||
|
"external_plugin_resources": self.external_plugin_resources,
|
||||||
|
}
|
||||||
|
defaults.update(kwargs)
|
||||||
|
return super().formfield(**defaults)
|
||||||
|
|
||||||
|
|
||||||
|
class RichTextFormField(forms.CharField):
|
||||||
|
widget = CKEditorWidget
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config_name="default",
|
||||||
|
extra_plugins=None,
|
||||||
|
external_plugin_resources=None,
|
||||||
|
*args,
|
||||||
|
**kwargs
|
||||||
|
):
|
||||||
|
kwargs["widget"] = self.widget(
|
||||||
|
config_name=config_name,
|
||||||
|
extra_plugins=extra_plugins,
|
||||||
|
external_plugin_resources=external_plugin_resources,
|
||||||
|
)
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{% load static %}
|
||||||
|
<div class="django-ckeditor-widget" data-field-id="{{ widget.attrs.id }}" style="display: inline-block;">
|
||||||
|
<textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} data-processed="0" data-config="{{ widget.config }}" data-external-plugin-resources="{{ widget.external_plugin_resources }}" data-id="{{ widget.attrs.id }}" data-type="ckeditortype">{% if widget.value %}{{ widget.value }}{% endif %}</textarea>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
from django import forms
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
|
from django.core.serializers.json import DjangoJSONEncoder
|
||||||
|
from django.templatetags.static import static
|
||||||
|
from django.utils.encoding import force_str
|
||||||
|
from django.utils.functional import Promise
|
||||||
|
from django.utils.translation import get_language
|
||||||
|
from js_asset import JS
|
||||||
|
|
||||||
|
from .configs import DEFAULT_CONFIG
|
||||||
|
|
||||||
|
|
||||||
|
class LazyEncoder(DjangoJSONEncoder):
|
||||||
|
def default(self, obj):
|
||||||
|
if isinstance(obj, Promise):
|
||||||
|
return force_str(obj)
|
||||||
|
return super().default(obj)
|
||||||
|
|
||||||
|
|
||||||
|
json_encode = LazyEncoder().encode
|
||||||
|
|
||||||
|
|
||||||
|
class CKEditorWidget(forms.Textarea):
|
||||||
|
"""
|
||||||
|
Widget providing CKEditor for Rich Text Editing.
|
||||||
|
Supports direct image uploads and embed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
template_name = "ckeditor/widget.html"
|
||||||
|
|
||||||
|
class Media:
|
||||||
|
js = (
|
||||||
|
JS(
|
||||||
|
"ckeditor/ckeditor-init.js",
|
||||||
|
{
|
||||||
|
"id": "ckeditor-init-script",
|
||||||
|
"data-ckeditor-basepath": getattr(
|
||||||
|
settings,
|
||||||
|
"CKEDITOR_BASEPATH",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
or static("ckeditor/ckeditor/"),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
"ckeditor/ckeditor/ckeditor.js",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config_name="default",
|
||||||
|
extra_plugins=None,
|
||||||
|
external_plugin_resources=None,
|
||||||
|
*args,
|
||||||
|
**kwargs
|
||||||
|
):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
self.config_name = config_name
|
||||||
|
# Setup config from defaults.
|
||||||
|
self.config = DEFAULT_CONFIG.copy()
|
||||||
|
|
||||||
|
# Try to get valid config from settings.
|
||||||
|
configs = getattr(settings, "CKEDITOR_CONFIGS", None)
|
||||||
|
if configs:
|
||||||
|
if isinstance(configs, dict):
|
||||||
|
# Make sure the config_name exists.
|
||||||
|
if self.config_name in configs:
|
||||||
|
config = configs[self.config_name]
|
||||||
|
# Make sure the configuration is a dictionary.
|
||||||
|
if not isinstance(config, dict):
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
'CKEDITOR_CONFIGS["%s"] \
|
||||||
|
setting must be a dictionary type.'
|
||||||
|
% self.config_name
|
||||||
|
)
|
||||||
|
# Override defaults with settings config.
|
||||||
|
self.config.update(config)
|
||||||
|
else:
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
"No configuration named '%s' \
|
||||||
|
found in your CKEDITOR_CONFIGS setting."
|
||||||
|
% self.config_name
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
"CKEDITOR_CONFIGS setting must be a\
|
||||||
|
dictionary type."
|
||||||
|
)
|
||||||
|
|
||||||
|
extra_plugins = extra_plugins or self.config.pop("extra_plugins", None) or []
|
||||||
|
|
||||||
|
if extra_plugins:
|
||||||
|
self.config["extraPlugins"] = ",".join(extra_plugins)
|
||||||
|
|
||||||
|
self.external_plugin_resources = (
|
||||||
|
external_plugin_resources
|
||||||
|
or self.config.pop("external_plugin_resources", None)
|
||||||
|
or []
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_context(self, name, value, attrs):
|
||||||
|
context = super().get_context(name, value, attrs)
|
||||||
|
|
||||||
|
self._set_config()
|
||||||
|
context["widget"]["config"] = json_encode(self.config)
|
||||||
|
|
||||||
|
external_plugin_resources = [
|
||||||
|
[force_str(a), force_str(b), force_str(c)]
|
||||||
|
for a, b, c in self.external_plugin_resources
|
||||||
|
]
|
||||||
|
context["widget"]["external_plugin_resources"] = json_encode(
|
||||||
|
external_plugin_resources
|
||||||
|
)
|
||||||
|
return context
|
||||||
|
|
||||||
|
def _set_config(self):
|
||||||
|
lang = get_language().lower()
|
||||||
|
if lang == "zh-hans":
|
||||||
|
lang = "zh-cn"
|
||||||
|
elif lang == "zh-hant":
|
||||||
|
lang = "zh"
|
||||||
|
self.config["language"] = lang
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,7 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from . import models
|
||||||
|
|
||||||
|
|
||||||
|
admin.site.register(models.ExampleModel)
|
||||||
|
admin.site.register(models.ExampleNonUploadModel)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class DemoApplicationConfig(AppConfig):
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
|
name = "ckeditor_demo.demo_application"
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
from django import forms
|
||||||
|
|
||||||
|
from ckeditor.fields import RichTextFormField
|
||||||
|
from ckeditor.widgets import CKEditorWidget
|
||||||
|
from ckeditor_uploader.fields import RichTextUploadingFormField
|
||||||
|
from ckeditor_uploader.widgets import CKEditorUploadingWidget
|
||||||
|
|
||||||
|
from .models import ExampleModel, ExampleNonUploadModel
|
||||||
|
from .widgets import CkEditorMultiWidget
|
||||||
|
|
||||||
|
|
||||||
|
class CkEditorForm(forms.Form):
|
||||||
|
ckeditor_standard_example = RichTextFormField()
|
||||||
|
ckeditor_upload_example = RichTextUploadingFormField(
|
||||||
|
config_name="my-custom-toolbar"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CkEditorMultiWidgetForm(forms.Form):
|
||||||
|
SUBWIDGET_SUFFIXES = ["0", "1"]
|
||||||
|
|
||||||
|
ckeditor_standard_multi_widget_example = forms.CharField(
|
||||||
|
widget=CkEditorMultiWidget(
|
||||||
|
widgets={suffix: CKEditorWidget for suffix in SUBWIDGET_SUFFIXES},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
ckeditor_upload_multi_widget_example = forms.CharField(
|
||||||
|
widget=CkEditorMultiWidget(
|
||||||
|
widgets={
|
||||||
|
suffix: CKEditorUploadingWidget(config_name="my-custom-toolbar")
|
||||||
|
for suffix in SUBWIDGET_SUFFIXES
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleModelForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = ExampleModel
|
||||||
|
fields = "__all__"
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleNonUploadModelForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = ExampleNonUploadModel
|
||||||
|
fields = "__all__"
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleModelOverriddenWidgetForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = ExampleModel
|
||||||
|
fields = "__all__"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
self.fields["content"].widget = CKEditorUploadingWidget(
|
||||||
|
config_name="my-custom-toolbar",
|
||||||
|
extra_plugins=["someplugin", "anotherplugin"],
|
||||||
|
external_plugin_resources=[
|
||||||
|
(
|
||||||
|
"someplugin",
|
||||||
|
"/static/path/to/someplugin/",
|
||||||
|
"plugin.js",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
# Generated by Django 4.0.3 on 2022-04-10 15:00
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
import ckeditor.fields
|
||||||
|
import ckeditor_uploader.fields
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = []
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="ExampleModel",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("content", ckeditor_uploader.fields.RichTextUploadingField()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="ExampleNonUploadModel",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("content", ckeditor.fields.RichTextField()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
Whitespace-only changes.
@@ -0,0 +1,12 @@
|
|||||||
|
from django.db import models
|
||||||
|
|
||||||
|
from ckeditor.fields import RichTextField
|
||||||
|
from ckeditor_uploader.fields import RichTextUploadingField
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleModel(models.Model):
|
||||||
|
content = RichTextUploadingField()
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleNonUploadModel(models.Model):
|
||||||
|
content = RichTextField()
|
||||||
Whitespace-only changes.
+16
@@ -0,0 +1,16 @@
|
|||||||
|
from django import test
|
||||||
|
|
||||||
|
from ckeditor_uploader import backends
|
||||||
|
|
||||||
|
|
||||||
|
class CustomBackend:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TestSelectingCustomBackend(test.SimpleTestCase):
|
||||||
|
@test.override_settings(
|
||||||
|
CKEDITOR_IMAGE_BACKEND="ckeditor_demo.demo_application.tests.test_custom_backend.CustomBackend"
|
||||||
|
)
|
||||||
|
def test_setting_returns_custom_backend(self):
|
||||||
|
result = backends.get_backend()
|
||||||
|
self.assertEqual(result, CustomBackend)
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
import os
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from django.test import RequestFactory, SimpleTestCase, TestCase
|
||||||
|
from django.test.utils import override_settings
|
||||||
|
|
||||||
|
from ckeditor_uploader import backends
|
||||||
|
from ckeditor_uploader.views import get_upload_filename
|
||||||
|
|
||||||
|
from .utils import get_absolute_name
|
||||||
|
|
||||||
|
|
||||||
|
MOCK_FILENAME = "some_filename.jpg"
|
||||||
|
GENERATOR_PREFIX = "some_folder"
|
||||||
|
GENERATED_MOCK_FILENAME = os.path.join(GENERATOR_PREFIX, MOCK_FILENAME)
|
||||||
|
|
||||||
|
|
||||||
|
def generator_with_filename_and_request(filename, _request):
|
||||||
|
return os.path.join(GENERATOR_PREFIX, filename)
|
||||||
|
|
||||||
|
|
||||||
|
def generator_with_only_filename(filename):
|
||||||
|
return os.path.join(GENERATOR_PREFIX, filename)
|
||||||
|
|
||||||
|
|
||||||
|
def generator_without_parameters():
|
||||||
|
return GENERATOR_PREFIX
|
||||||
|
|
||||||
|
|
||||||
|
class TestUploadFilenameGeneratorParameters(TestCase):
|
||||||
|
fixtures = ["test_admin.json"]
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.mock_request = RequestFactory().request()
|
||||||
|
self.mock_request.user = User.objects.get(username="test")
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
CKEDITOR_FILENAME_GENERATOR=get_absolute_name(
|
||||||
|
generator_with_filename_and_request
|
||||||
|
)
|
||||||
|
)
|
||||||
|
def test_compatible_parameters(self):
|
||||||
|
# `self.assertWarns()` is not available in Python 2
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter("always")
|
||||||
|
|
||||||
|
generated_filename = get_upload_filename(MOCK_FILENAME, self.mock_request)
|
||||||
|
self.assertEqual(len(w), 0)
|
||||||
|
|
||||||
|
self.assertIn(GENERATED_MOCK_FILENAME, generated_filename)
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
CKEDITOR_FILENAME_GENERATOR=get_absolute_name(generator_with_only_filename)
|
||||||
|
)
|
||||||
|
def test_no_request_parameter_deprecation_warning(self):
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter("always")
|
||||||
|
|
||||||
|
generated_filename = get_upload_filename(MOCK_FILENAME, self.mock_request)
|
||||||
|
self.assertEqual(len(w), 1)
|
||||||
|
self.assertTrue(issubclass(w[0].category, PendingDeprecationWarning))
|
||||||
|
|
||||||
|
self.assertIn(GENERATED_MOCK_FILENAME, generated_filename)
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
CKEDITOR_FILENAME_GENERATOR=get_absolute_name(generator_without_parameters)
|
||||||
|
)
|
||||||
|
def test_incompatible_parameters(self):
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter("always")
|
||||||
|
|
||||||
|
generated_filename = get_upload_filename(MOCK_FILENAME, self.mock_request)
|
||||||
|
self.assertEqual(len(w), 1)
|
||||||
|
|
||||||
|
self.assertIn(MOCK_FILENAME, generated_filename)
|
||||||
|
self.assertNotIn(GENERATOR_PREFIX, generated_filename)
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeprecatedImageBackendValues(SimpleTestCase):
|
||||||
|
@override_settings(CKEDITOR_IMAGE_BACKEND="pillow")
|
||||||
|
def test_pillow_setting(self):
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter("always")
|
||||||
|
result = backends.get_backend()
|
||||||
|
self.assertEqual(len(w), 1)
|
||||||
|
self.assertEqual(result, backends.PillowBackend)
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_IMAGE_BACKEND=None)
|
||||||
|
def test_none_setting(self):
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter("always")
|
||||||
|
result = backends.get_backend()
|
||||||
|
self.assertEqual(len(w), 1)
|
||||||
|
self.assertEqual(result, backends.DummyBackend)
|
||||||
+112
@@ -0,0 +1,112 @@
|
|||||||
|
import json
|
||||||
|
import os.path
|
||||||
|
|
||||||
|
from django.contrib.staticfiles.finders import find
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.test.utils import override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from .utils import get_absolute_media_path, get_media_url, remove_upload_directory, sha1
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_IMAGE_BACKEND="ckeditor_uploader.backends.DummyBackend")
|
||||||
|
class DummyTestCase(TestCase):
|
||||||
|
fixtures = ["test_admin.json"]
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
remove_upload_directory()
|
||||||
|
|
||||||
|
def assertJsonResponse(self, response, expected_data):
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
data = json.loads(response.content)
|
||||||
|
self.assertEqual(data, expected_data)
|
||||||
|
|
||||||
|
def test_upload_file(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/LICENSE.md")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "license.md",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("license.md"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("license.md")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_ALLOW_NONIMAGE_FILES=False)
|
||||||
|
def test_upload_file_disabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/LICENSE.md")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
self.assertContains(response, "Invalid file type.")
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_ALLOW_NONIMAGE_FILES=False)
|
||||||
|
def test_upload_png(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/skins/moono/images/hidpi/close.png")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "close.png",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("close.png"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("close.png")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
|
||||||
|
def test_upload_jpg(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find(
|
||||||
|
"ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/pojoaque.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "pojoaque.jpg",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("pojoaque.jpg"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("pojoaque.jpg")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
|
||||||
|
def test_upload_gif(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/galleriffic/css/loader.gif")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "loader.gif",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("loader.gif"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("loader.gif")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
from http import HTTPStatus
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from ckeditor.fields import RichTextFormField
|
||||||
|
from ckeditor.widgets import CKEditorWidget
|
||||||
|
from ckeditor_uploader.fields import RichTextUploadingFormField
|
||||||
|
from ckeditor_uploader.widgets import CKEditorUploadingWidget
|
||||||
|
|
||||||
|
from ..forms import (
|
||||||
|
ExampleModelForm,
|
||||||
|
ExampleModelOverriddenWidgetForm,
|
||||||
|
ExampleNonUploadModelForm,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ModelFieldAndFormFieldTestCase(TestCase):
|
||||||
|
def test_non_upload_model_form_contains_expected_formfield(self):
|
||||||
|
form = ExampleNonUploadModelForm()
|
||||||
|
self.assert_form_contains_expected_formfield_with_default_widget_options(
|
||||||
|
form, "content", RichTextFormField, CKEditorWidget
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_upload_model_form_contains_expected_formfield(self):
|
||||||
|
form = ExampleModelForm()
|
||||||
|
self.assert_form_contains_expected_formfield_with_default_widget_options(
|
||||||
|
form, "content", RichTextUploadingFormField, CKEditorUploadingWidget
|
||||||
|
)
|
||||||
|
|
||||||
|
def assert_form_contains_expected_formfield_with_default_widget_options(
|
||||||
|
self, form, field_name, expected_field_type, expected_widget_type
|
||||||
|
):
|
||||||
|
form_field = form.fields[field_name]
|
||||||
|
self.assertIs(type(form_field), expected_field_type)
|
||||||
|
widget = form_field.widget
|
||||||
|
self.assertIs(type(widget), expected_widget_type)
|
||||||
|
self.assertEqual(widget.config_name, "default")
|
||||||
|
self.assertEqual(widget.config.get("extraPlugins"), None)
|
||||||
|
self.assertListEqual(widget.external_plugin_resources, [])
|
||||||
|
|
||||||
|
def test_upload_model_form_with_overridden_widget_contains_expected_formfield(self):
|
||||||
|
form = ExampleModelOverriddenWidgetForm()
|
||||||
|
form_field = form.fields["content"]
|
||||||
|
self.assertIs(type(form_field), RichTextUploadingFormField)
|
||||||
|
widget = form_field.widget
|
||||||
|
self.assertIs(type(widget), CKEditorUploadingWidget)
|
||||||
|
self.assertEqual(widget.config_name, "my-custom-toolbar")
|
||||||
|
self.assertEqual(widget.config.get("extraPlugins"), "someplugin,anotherplugin")
|
||||||
|
self.assertListEqual(
|
||||||
|
widget.external_plugin_resources,
|
||||||
|
[
|
||||||
|
(
|
||||||
|
"someplugin",
|
||||||
|
"/static/path/to/someplugin/",
|
||||||
|
"plugin.js",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_admin_model_forms_contain_expected_formfields(self):
|
||||||
|
superuser = get_user_model().objects.create_user(
|
||||||
|
username="superuser", is_superuser=True, is_staff=True
|
||||||
|
)
|
||||||
|
self.client.force_login(superuser)
|
||||||
|
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("admin:demo_application_examplenonuploadmodel_add")
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, HTTPStatus.OK)
|
||||||
|
|
||||||
|
form = response.context["adminform"].form
|
||||||
|
self.assert_form_contains_expected_formfield_with_default_widget_options(
|
||||||
|
form, "content", RichTextFormField, CKEditorWidget
|
||||||
|
)
|
||||||
|
|
||||||
|
response = self.client.get(reverse("admin:demo_application_examplemodel_add"))
|
||||||
|
self.assertEqual(response.status_code, HTTPStatus.OK)
|
||||||
|
|
||||||
|
form = response.context["adminform"].form
|
||||||
|
self.assert_form_contains_expected_formfield_with_default_widget_options(
|
||||||
|
form, "content", RichTextUploadingFormField, CKEditorUploadingWidget
|
||||||
|
)
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
import json
|
||||||
|
import os.path
|
||||||
|
|
||||||
|
from django.contrib.staticfiles.finders import find
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.test.utils import override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from .utils import get_absolute_media_path, get_media_url, remove_upload_directory, sha1
|
||||||
|
|
||||||
|
|
||||||
|
class PillowTestCase(TestCase):
|
||||||
|
fixtures = ["test_admin.json"]
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
remove_upload_directory()
|
||||||
|
|
||||||
|
def assertJsonResponse(self, response, expected_data):
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
data = json.loads(response.content)
|
||||||
|
self.assertEqual(data, expected_data)
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_ALLOW_NONIMAGE_FILES=False)
|
||||||
|
def test_upload_file_disabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/LICENSE.md")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
self.assertContains(response, "Invalid file type.")
|
||||||
|
|
||||||
|
def test_upload_file(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/LICENSE.md")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "license.md",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("license.md"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("license.md")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(os.path.getsize(filepath), os.path.getsize(upload))
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=True)
|
||||||
|
def test_upload_file_with_compression_enabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/LICENSE.md")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "license.md",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("license.md"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("license.md")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertEqual(os.path.getsize(filepath), os.path.getsize(upload))
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=False)
|
||||||
|
def test_upload_jpg(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find(
|
||||||
|
"ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/pojoaque.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "pojoaque.jpg",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("pojoaque.jpg"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("pojoaque.jpg")
|
||||||
|
thumb = get_absolute_media_path("pojoaque_thumb.jpg")
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
self.assertEqual(1186, os.path.getsize(upload))
|
||||||
|
self.assertEqual(1144, os.path.getsize(thumb))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=True)
|
||||||
|
def test_upload_jpg_compression_enabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find(
|
||||||
|
"ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/pojoaque.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "pojoaque.jpg",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("pojoaque.jpg"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("pojoaque.jpg")
|
||||||
|
thumb = get_absolute_media_path("pojoaque_thumb.jpg")
|
||||||
|
self.assertEqual(598, os.path.getsize(upload))
|
||||||
|
self.assertEqual(637, os.path.getsize(thumb))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=False)
|
||||||
|
def test_upload_png(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/skins/moono/images/hidpi/close.png")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "close.png",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("close.png"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("close.png")
|
||||||
|
thumb = get_absolute_media_path("close_thumb.png")
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
self.assertEqual(1271, os.path.getsize(upload))
|
||||||
|
self.assertEqual(744, os.path.getsize(thumb))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=True)
|
||||||
|
def test_upload_png_with_compression_enabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/ckeditor/skins/moono/images/hidpi/close.png")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "close.jpg",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("close.jpg"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("close.jpg")
|
||||||
|
thumb = get_absolute_media_path("close_thumb.jpg")
|
||||||
|
self.assertTrue(os.path.isfile(upload), upload)
|
||||||
|
self.assertTrue(os.path.isfile(thumb), thumb)
|
||||||
|
self.assertEqual(575, os.path.getsize(upload))
|
||||||
|
self.assertEqual(642, os.path.getsize(thumb))
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=False)
|
||||||
|
def test_upload_gif(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/galleriffic/css/loader.gif")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "loader.gif",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("loader.gif"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("loader.gif")
|
||||||
|
thumb = get_absolute_media_path("loader_thumb.gif")
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
self.assertEqual(10453, os.path.getsize(upload))
|
||||||
|
self.assertFalse(os.path.exists(thumb), thumb)
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_FORCE_JPEG_COMPRESSION=True)
|
||||||
|
def test_upload_gif_with_compression_enabled(self):
|
||||||
|
self.client.login(username="test", password="test")
|
||||||
|
|
||||||
|
filepath = find("ckeditor/galleriffic/css/loader.gif")
|
||||||
|
|
||||||
|
with open(filepath, "rb") as fp:
|
||||||
|
response = self.client.post(reverse("ckeditor_upload"), {"upload": fp})
|
||||||
|
self.assertJsonResponse(
|
||||||
|
response,
|
||||||
|
{
|
||||||
|
"fileName": "loader.gif",
|
||||||
|
"uploaded": "1",
|
||||||
|
"url": get_media_url("loader.gif"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
upload = get_absolute_media_path("loader.gif")
|
||||||
|
thumb = get_absolute_media_path("loader_thumb.gif")
|
||||||
|
self.assertEqual(sha1(filepath), sha1(upload))
|
||||||
|
self.assertEqual(10453, os.path.getsize(upload))
|
||||||
|
self.assertFalse(os.path.exists(thumb), thumb)
|
||||||
+142
@@ -0,0 +1,142 @@
|
|||||||
|
from http import HTTPStatus
|
||||||
|
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from ckeditor.widgets import json_encode
|
||||||
|
|
||||||
|
from ..forms import CkEditorMultiWidgetForm
|
||||||
|
from .utils import get_config, get_contexts_for_widgets
|
||||||
|
|
||||||
|
|
||||||
|
class WidgetContextTestCase(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# Facilitates printing the whole diff if the tests fail
|
||||||
|
self.maxDiff = None
|
||||||
|
|
||||||
|
def test_rendered_ckeditor_widgets_contain_expected_context(self):
|
||||||
|
response = self.client.get(reverse("ckeditor-form"))
|
||||||
|
self.assertEqual(response.status_code, HTTPStatus.OK)
|
||||||
|
|
||||||
|
widget_contexts = get_contexts_for_widgets(response)
|
||||||
|
|
||||||
|
field_name__config__tuples = (
|
||||||
|
(
|
||||||
|
"ckeditor_standard_example",
|
||||||
|
{
|
||||||
|
**get_config("default"),
|
||||||
|
"language": "en-us",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"ckeditor_upload_example",
|
||||||
|
{
|
||||||
|
**get_config("my-custom-toolbar"),
|
||||||
|
"filebrowserUploadUrl": reverse("ckeditor_upload"),
|
||||||
|
"filebrowserBrowseUrl": reverse("ckeditor_browse"),
|
||||||
|
"language": "en-us",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.assertEqual(len(widget_contexts), len(field_name__config__tuples))
|
||||||
|
|
||||||
|
for field_name, expected_config in field_name__config__tuples:
|
||||||
|
with self.subTest(field_name=field_name):
|
||||||
|
widget_id = f"id_{field_name}"
|
||||||
|
self.assertIn(widget_id, widget_contexts)
|
||||||
|
widget_context = widget_contexts[widget_id]
|
||||||
|
|
||||||
|
expected_widget_context = self.get_expected_widget_context(
|
||||||
|
field_name,
|
||||||
|
widget_id,
|
||||||
|
expected_config,
|
||||||
|
)
|
||||||
|
self.assertDictEqual(widget_context, expected_widget_context)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_expected_widget_context(field_name, widget_id, expected_config: dict):
|
||||||
|
return {
|
||||||
|
"widget": {
|
||||||
|
"name": field_name,
|
||||||
|
"is_hidden": False,
|
||||||
|
"required": True,
|
||||||
|
"value": None,
|
||||||
|
"attrs": {
|
||||||
|
"cols": "40",
|
||||||
|
"rows": "10",
|
||||||
|
"required": True,
|
||||||
|
"id": widget_id,
|
||||||
|
},
|
||||||
|
"template_name": "ckeditor/widget.html",
|
||||||
|
"config": json_encode(expected_config),
|
||||||
|
"external_plugin_resources": "[]",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_rendered_ckeditor_multi_widgets_contain_expected_context(self):
|
||||||
|
response = self.client.get(reverse("ckeditor-multi-widget-form"))
|
||||||
|
self.assertEqual(response.status_code, HTTPStatus.OK)
|
||||||
|
|
||||||
|
widget_contexts = get_contexts_for_widgets(response)
|
||||||
|
|
||||||
|
field_name__config__tuples = (
|
||||||
|
(
|
||||||
|
"ckeditor_standard_multi_widget_example",
|
||||||
|
{
|
||||||
|
**get_config("default"),
|
||||||
|
"language": "en-us",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"ckeditor_upload_multi_widget_example",
|
||||||
|
{
|
||||||
|
**get_config("my-custom-toolbar"),
|
||||||
|
"filebrowserUploadUrl": reverse("ckeditor_upload"),
|
||||||
|
"filebrowserBrowseUrl": reverse("ckeditor_browse"),
|
||||||
|
"language": "en-us",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.assertEqual(len(widget_contexts), len(field_name__config__tuples))
|
||||||
|
|
||||||
|
for field_name, expected_config in field_name__config__tuples:
|
||||||
|
with self.subTest(field_name=field_name):
|
||||||
|
widget_id = f"id_{field_name}"
|
||||||
|
self.assertIn(widget_id, widget_contexts)
|
||||||
|
widget_context = widget_contexts[widget_id]
|
||||||
|
|
||||||
|
expected_widget_context = self.get_expected_multi_widget_context(
|
||||||
|
field_name, widget_id, expected_config
|
||||||
|
)
|
||||||
|
self.assertDictEqual(widget_context, expected_widget_context)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_expected_multi_widget_context(
|
||||||
|
cls, field_name, widget_id, expected_config: dict
|
||||||
|
):
|
||||||
|
subwidget_contexts = []
|
||||||
|
for subwidget_suffix in CkEditorMultiWidgetForm.SUBWIDGET_SUFFIXES:
|
||||||
|
expected_widget_context = cls.get_expected_widget_context(
|
||||||
|
f"{field_name}_{subwidget_suffix}",
|
||||||
|
f"{widget_id}_{subwidget_suffix}",
|
||||||
|
expected_config,
|
||||||
|
)
|
||||||
|
# The multi-widget only uses the contents of the `widget` context variable
|
||||||
|
subwidget_context = expected_widget_context["widget"]
|
||||||
|
# Each subwidget is non-required (even if its `required` attr is True)
|
||||||
|
subwidget_context["required"] = False
|
||||||
|
subwidget_contexts.append(subwidget_context)
|
||||||
|
return {
|
||||||
|
"widget": {
|
||||||
|
"name": field_name,
|
||||||
|
"is_hidden": False,
|
||||||
|
"required": True,
|
||||||
|
"value": None,
|
||||||
|
"attrs": {
|
||||||
|
"required": True,
|
||||||
|
"id": widget_id,
|
||||||
|
},
|
||||||
|
"template_name": "django/forms/widgets/multiwidget.html",
|
||||||
|
"subwidgets": subwidget_contexts,
|
||||||
|
},
|
||||||
|
}
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
import os
|
||||||
|
import os.path
|
||||||
|
from time import sleep
|
||||||
|
from unittest import skipUnless
|
||||||
|
|
||||||
|
from django.contrib.staticfiles.finders import find
|
||||||
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
|
||||||
|
from django.test.utils import override_settings
|
||||||
|
from selenium import webdriver
|
||||||
|
|
||||||
|
from .utils import get_upload_directory, remove_upload_directory, sha1
|
||||||
|
|
||||||
|
|
||||||
|
CHROMIUM = "chromium"
|
||||||
|
FIREFOX = "firefox"
|
||||||
|
SELENIUM = os.environ.get("SELENIUM")
|
||||||
|
|
||||||
|
|
||||||
|
@skipUnless(
|
||||||
|
SELENIUM,
|
||||||
|
"Set the SELENIUM env variable to 'firefox' or 'chromium' to run selenium tests",
|
||||||
|
)
|
||||||
|
class TestAdminPanelWidget(StaticLiveServerTestCase):
|
||||||
|
fixtures = ["test_admin.json"]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
if SELENIUM == CHROMIUM:
|
||||||
|
options = webdriver.ChromeOptions()
|
||||||
|
options.add_argument("--headless")
|
||||||
|
options.add_argument("--disable-gpu")
|
||||||
|
cls.selenium = webdriver.Chrome(chrome_options=options)
|
||||||
|
elif SELENIUM == FIREFOX:
|
||||||
|
cls.selenium = webdriver.Firefox()
|
||||||
|
super().setUpClass()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
cls.selenium.quit()
|
||||||
|
super().tearDownClass()
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
remove_upload_directory()
|
||||||
|
|
||||||
|
def test_admin_panel_widget(self):
|
||||||
|
self._login_to_admin()
|
||||||
|
self._go_to_demo_application_in_admin()
|
||||||
|
self._assert_editor_loaded()
|
||||||
|
self._focus_cursor_in_editor()
|
||||||
|
self._enter_test_text()
|
||||||
|
self._open_image_upload_widget()
|
||||||
|
self._go_to_upload_tab()
|
||||||
|
self._switch_to_form_iframe()
|
||||||
|
self._upload_image()
|
||||||
|
self._assert_image_uploaded()
|
||||||
|
|
||||||
|
def _login_to_admin(self):
|
||||||
|
self.selenium.get("{}{}".format(self.live_server_url, "/admin/"))
|
||||||
|
username_input = self.selenium.find_element_by_name("username")
|
||||||
|
username_input.send_keys("test")
|
||||||
|
password_input = self.selenium.find_element_by_name("password")
|
||||||
|
password_input.send_keys("test")
|
||||||
|
self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()
|
||||||
|
|
||||||
|
def _go_to_demo_application_in_admin(self):
|
||||||
|
self.selenium.get(
|
||||||
|
"{}{}".format(
|
||||||
|
self.live_server_url, "/admin/demo_application/examplemodel/add/"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def _assert_editor_loaded(self):
|
||||||
|
sleep(2)
|
||||||
|
self.selenium.find_element_by_id("cke_id_content")
|
||||||
|
|
||||||
|
def _focus_cursor_in_editor(self):
|
||||||
|
self.frame = self.selenium.find_element_by_class_name("cke_wysiwyg_frame")
|
||||||
|
self.frame.click()
|
||||||
|
|
||||||
|
def _enter_test_text(self):
|
||||||
|
self.frame.send_keys("test")
|
||||||
|
|
||||||
|
def _open_image_upload_widget(self):
|
||||||
|
self.selenium.find_element_by_css_selector(
|
||||||
|
"span.cke_button_icon.cke_button__image_icon"
|
||||||
|
).click()
|
||||||
|
sleep(1)
|
||||||
|
|
||||||
|
def _go_to_upload_tab(self):
|
||||||
|
self.selenium.find_element_by_css_selector("a[title='Upload']").click()
|
||||||
|
sleep(1)
|
||||||
|
|
||||||
|
def _switch_to_form_iframe(self):
|
||||||
|
iframe = self.selenium.find_element_by_css_selector(
|
||||||
|
"iframe.cke_dialog_ui_input_file"
|
||||||
|
)
|
||||||
|
self.selenium.switch_to.frame(iframe)
|
||||||
|
|
||||||
|
def _upload_image(self):
|
||||||
|
input = self.selenium.find_element_by_css_selector("input[type=file]")
|
||||||
|
input.send_keys(self._get_upload_file())
|
||||||
|
self.selenium.switch_to.default_content()
|
||||||
|
self.selenium.find_element_by_class_name("cke_dialog_ui_fileButton").click()
|
||||||
|
sleep(2)
|
||||||
|
|
||||||
|
def _get_upload_file(self):
|
||||||
|
return find("ckeditor/ckeditor/skins/moono/images/hidpi/close.png")
|
||||||
|
|
||||||
|
def _assert_image_uploaded(self):
|
||||||
|
upload_directory = get_upload_directory()
|
||||||
|
expected_image_path = os.path.join(upload_directory, "close.png")
|
||||||
|
expected_thumbnail_path = os.path.join(upload_directory, "close_thumb.png")
|
||||||
|
self.assertTrue(os.path.isfile(expected_image_path))
|
||||||
|
self.assertTrue(os.path.isfile(expected_thumbnail_path))
|
||||||
|
self._assert_uploaded_image_did_not_changed(expected_image_path)
|
||||||
|
self._assert_thumbnail_is_not_empty(expected_thumbnail_path)
|
||||||
|
os.remove(expected_image_path)
|
||||||
|
os.remove(expected_thumbnail_path)
|
||||||
|
|
||||||
|
def _assert_uploaded_image_did_not_changed(self, path):
|
||||||
|
expected_sha = sha1(self._get_upload_file())
|
||||||
|
uploaded_sha = sha1(path)
|
||||||
|
self.assertEqual(expected_sha, uploaded_sha)
|
||||||
|
|
||||||
|
def _assert_thumbnail_is_not_empty(self, path):
|
||||||
|
size = os.path.getsize(path)
|
||||||
|
assert size > 0
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(CKEDITOR_IMAGE_BACKEND="ckeditor_uploader.backends.DummyBackend")
|
||||||
|
class TestAdminPanelWidgetForDummyImageBackend(TestAdminPanelWidget):
|
||||||
|
def _assert_image_uploaded(self):
|
||||||
|
upload_directory = get_upload_directory()
|
||||||
|
expected_image_path = os.path.join(upload_directory, "close.png")
|
||||||
|
expected_thumbnail_path = os.path.join(upload_directory, "close_thumb.png")
|
||||||
|
self.assertTrue(os.path.isfile(expected_image_path), expected_image_path)
|
||||||
|
self.assertFalse(
|
||||||
|
os.path.exists(expected_thumbnail_path), expected_thumbnail_path
|
||||||
|
)
|
||||||
|
self._assert_uploaded_image_did_not_changed(expected_image_path)
|
||||||
|
os.remove(expected_image_path)
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
import hashlib
|
||||||
|
import os.path
|
||||||
|
import shutil
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Dict
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
from ckeditor.configs import DEFAULT_CONFIG
|
||||||
|
|
||||||
|
|
||||||
|
def get_upload_directory():
|
||||||
|
date_path = datetime.now().strftime("%Y/%m/%d")
|
||||||
|
|
||||||
|
# Complete upload path (upload_path + date_path).
|
||||||
|
upload_path = os.path.join(settings.CKEDITOR_UPLOAD_PATH, date_path)
|
||||||
|
return os.path.join(settings.MEDIA_ROOT, upload_path)
|
||||||
|
|
||||||
|
|
||||||
|
def get_media_url(fname):
|
||||||
|
args = [settings.CKEDITOR_UPLOAD_PATH, datetime.now().strftime("%Y/%m/%d"), fname]
|
||||||
|
return settings.MEDIA_URL + "/".join(arg.strip("/") for arg in args)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_upload_directory():
|
||||||
|
# Called on test setup
|
||||||
|
# Avoid falling in the use case chere django append a hash to the file name
|
||||||
|
# to prevent file collisions
|
||||||
|
shutil.rmtree(get_upload_directory(), ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def sha1(path):
|
||||||
|
image = open(path, "rb")
|
||||||
|
fhash = hashlib.sha1()
|
||||||
|
fhash.update(image.read())
|
||||||
|
return fhash.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def get_absolute_media_path(fname):
|
||||||
|
upload_directory = get_upload_directory()
|
||||||
|
return os.path.join(upload_directory, fname)
|
||||||
|
|
||||||
|
|
||||||
|
def get_absolute_name(class_or_function):
|
||||||
|
return f"{class_or_function.__module__}.{class_or_function.__name__}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_config(config_name):
|
||||||
|
return {
|
||||||
|
**DEFAULT_CONFIG,
|
||||||
|
**settings.CKEDITOR_CONFIGS[config_name],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_contexts_for_widgets(response) -> Dict[str, Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Searches through the response's context for subcontexts of widgets,
|
||||||
|
and returns a dictionary with the widgets' `id` attribute as key
|
||||||
|
and the widget's context dictionary as value.
|
||||||
|
"""
|
||||||
|
widget_contexts = {}
|
||||||
|
for subcontext in response.context:
|
||||||
|
if "widget" not in subcontext:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for subcontext_dict in subcontext:
|
||||||
|
if type(subcontext_dict) is not dict or "widget" not in subcontext_dict:
|
||||||
|
continue
|
||||||
|
|
||||||
|
widget = subcontext_dict["widget"]
|
||||||
|
widget_id = widget["attrs"]["id"]
|
||||||
|
widget_contexts[widget_id] = subcontext_dict
|
||||||
|
|
||||||
|
return widget_contexts
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
from django.urls import reverse
|
||||||
|
from django.views import generic
|
||||||
|
|
||||||
|
from . import forms
|
||||||
|
|
||||||
|
|
||||||
|
class CkEditorFormView(generic.FormView):
|
||||||
|
form_class = forms.CkEditorForm
|
||||||
|
template_name = "form.html"
|
||||||
|
|
||||||
|
def get_success_url(self):
|
||||||
|
return reverse("ckeditor-form")
|
||||||
|
|
||||||
|
|
||||||
|
class CkEditorMultiWidgetFormView(generic.FormView):
|
||||||
|
form_class = forms.CkEditorMultiWidgetForm
|
||||||
|
template_name = "form.html"
|
||||||
|
|
||||||
|
def get_success_url(self):
|
||||||
|
return reverse("ckeditor-multi-widget-form")
|
||||||
|
|
||||||
|
|
||||||
|
ckeditor_form_view = CkEditorFormView.as_view()
|
||||||
|
ckeditor_multi_widget_form_view = CkEditorMultiWidgetFormView.as_view()
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from django.forms import MultiWidget
|
||||||
|
|
||||||
|
|
||||||
|
class CkEditorMultiWidget(MultiWidget):
|
||||||
|
def decompress(self, value):
|
||||||
|
return [value for _ in self.widgets]
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
Django settings for ckeditor_demo project.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/1.6/topics/settings/
|
||||||
|
|
||||||
|
For the full list of settings and their values, see
|
||||||
|
https://docs.djangoproject.com/en/1.6/ref/settings/
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||||
|
|
||||||
|
|
||||||
|
# Quick-start development settings - unsuitable for production
|
||||||
|
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
|
||||||
|
|
||||||
|
# SECURITY WARNING: keep the secret key used in production secret!
|
||||||
|
SECRET_KEY = "cwog(6mx-+m9-@*n7jsn+*q4in*+nss_nv+s0da39ail@=x(ne"
|
||||||
|
|
||||||
|
# SECURITY WARNING: don't run with debug turned on in production!
|
||||||
|
DEBUG = True
|
||||||
|
|
||||||
|
TEMPLATES = [
|
||||||
|
{
|
||||||
|
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||||
|
"DIRS": [],
|
||||||
|
"APP_DIRS": True,
|
||||||
|
"OPTIONS": {
|
||||||
|
"context_processors": [
|
||||||
|
"django.template.context_processors.debug",
|
||||||
|
"django.template.context_processors.request",
|
||||||
|
"django.contrib.auth.context_processors.auth",
|
||||||
|
"django.contrib.messages.context_processors.messages",
|
||||||
|
],
|
||||||
|
"debug": DEBUG,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
ALLOWED_HOSTS = []
|
||||||
|
|
||||||
|
CACHED_STORAGE = False
|
||||||
|
|
||||||
|
if CACHED_STORAGE:
|
||||||
|
DEFAULT_FILE_STORAGE = "django.contrib.staticfiles.storage.CachedStaticFilesStorage"
|
||||||
|
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.CachedStaticFilesStorage"
|
||||||
|
STATICFILES_FINDERS = (
|
||||||
|
"django.contrib.staticfiles.finders.FileSystemFinder",
|
||||||
|
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
|
||||||
|
"django.contrib.staticfiles.finders.DefaultStorageFinder",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Application definition
|
||||||
|
|
||||||
|
INSTALLED_APPS = (
|
||||||
|
"django.contrib.admin",
|
||||||
|
"django.contrib.auth",
|
||||||
|
"django.contrib.contenttypes",
|
||||||
|
"django.contrib.sessions",
|
||||||
|
"django.contrib.messages",
|
||||||
|
"django.contrib.staticfiles",
|
||||||
|
"django_extensions",
|
||||||
|
"ckeditor",
|
||||||
|
"ckeditor_uploader",
|
||||||
|
"ckeditor_demo.demo_application",
|
||||||
|
)
|
||||||
|
|
||||||
|
MIDDLEWARE = [
|
||||||
|
"django.middleware.security.SecurityMiddleware",
|
||||||
|
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||||
|
"django.middleware.common.CommonMiddleware",
|
||||||
|
"django.middleware.csrf.CsrfViewMiddleware",
|
||||||
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
|
"django.contrib.messages.middleware.MessageMiddleware",
|
||||||
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
|
]
|
||||||
|
|
||||||
|
ROOT_URLCONF = "ckeditor_demo.urls"
|
||||||
|
|
||||||
|
WSGI_APPLICATION = "ckeditor_demo.wsgi.application"
|
||||||
|
|
||||||
|
|
||||||
|
# Database
|
||||||
|
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
|
||||||
|
|
||||||
|
DATABASES = {
|
||||||
|
"default": {
|
||||||
|
"ENGINE": "django.db.backends.sqlite3",
|
||||||
|
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||||
|
|
||||||
|
# Internationalization
|
||||||
|
# https://docs.djangoproject.com/en/1.6/topics/i18n/
|
||||||
|
|
||||||
|
LANGUAGE_CODE = "en-us"
|
||||||
|
|
||||||
|
TIME_ZONE = "UTC"
|
||||||
|
|
||||||
|
USE_I18N = True
|
||||||
|
|
||||||
|
USE_L10N = True
|
||||||
|
|
||||||
|
USE_TZ = True
|
||||||
|
|
||||||
|
# Static files (CSS, JavaScript, Images)
|
||||||
|
# https://docs.djangoproject.com/en/1.6/howto/static-files/
|
||||||
|
|
||||||
|
STATIC_URL = "/static/"
|
||||||
|
MEDIA_URL = "/media/"
|
||||||
|
STATIC_ROOT = os.path.join(tempfile.gettempdir(), "ck_static")
|
||||||
|
MEDIA_ROOT = os.path.join(tempfile.gettempdir(), "ck_media")
|
||||||
|
|
||||||
|
from ckeditor.configs import DEFAULT_CONFIG # noqa
|
||||||
|
|
||||||
|
|
||||||
|
CKEDITOR_UPLOAD_PATH = "uploads/"
|
||||||
|
CKEDITOR_IMAGE_BACKEND = "ckeditor_uploader.backends.PillowBackend"
|
||||||
|
CKEDITOR_THUMBNAIL_SIZE = (300, 300)
|
||||||
|
CKEDITOR_IMAGE_QUALITY = 40
|
||||||
|
CKEDITOR_BROWSE_SHOW_DIRS = True
|
||||||
|
CKEDITOR_ALLOW_NONIMAGE_FILES = True
|
||||||
|
|
||||||
|
CUSTOM_TOOLBAR = [
|
||||||
|
{
|
||||||
|
"name": "document",
|
||||||
|
"items": [
|
||||||
|
"Styles",
|
||||||
|
"Format",
|
||||||
|
"Bold",
|
||||||
|
"Italic",
|
||||||
|
"Underline",
|
||||||
|
"Strike",
|
||||||
|
"-",
|
||||||
|
"TextColor",
|
||||||
|
"BGColor",
|
||||||
|
"-",
|
||||||
|
"JustifyLeft",
|
||||||
|
"JustifyCenter",
|
||||||
|
"JustifyRight",
|
||||||
|
"JustifyBlock",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "widgets",
|
||||||
|
"items": [
|
||||||
|
"Undo",
|
||||||
|
"Redo",
|
||||||
|
"-",
|
||||||
|
"NumberedList",
|
||||||
|
"BulletedList",
|
||||||
|
"-",
|
||||||
|
"Outdent",
|
||||||
|
"Indent",
|
||||||
|
"-",
|
||||||
|
"Link",
|
||||||
|
"Unlink",
|
||||||
|
"-",
|
||||||
|
"Image",
|
||||||
|
"CodeSnippet",
|
||||||
|
"Table",
|
||||||
|
"HorizontalRule",
|
||||||
|
"Smiley",
|
||||||
|
"SpecialChar",
|
||||||
|
"-",
|
||||||
|
"Blockquote",
|
||||||
|
"-",
|
||||||
|
"ShowBlocks",
|
||||||
|
"Maximize",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
CKEDITOR_CONFIGS = {
|
||||||
|
"default": DEFAULT_CONFIG,
|
||||||
|
"my-custom-toolbar": {
|
||||||
|
"skin": "moono-lisa",
|
||||||
|
"toolbar": CUSTOM_TOOLBAR,
|
||||||
|
"toolbarGroups": None,
|
||||||
|
"extraPlugins": ",".join(["image2", "codesnippet"]),
|
||||||
|
"removePlugins": ",".join(["image"]),
|
||||||
|
"codeSnippet_theme": "xcode",
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.conf.urls.static import static
|
||||||
|
from django.contrib import admin
|
||||||
|
from django.urls import include, re_path
|
||||||
|
|
||||||
|
from .demo_application import views
|
||||||
|
|
||||||
|
|
||||||
|
urlpatterns = (
|
||||||
|
[
|
||||||
|
re_path(r"^$", views.ckeditor_form_view, name="ckeditor-form"),
|
||||||
|
re_path(
|
||||||
|
r"^multiwidget/$",
|
||||||
|
views.ckeditor_multi_widget_form_view,
|
||||||
|
name="ckeditor-multi-widget-form",
|
||||||
|
),
|
||||||
|
re_path(r"^admin/", admin.site.urls),
|
||||||
|
re_path(r"^ckeditor/", include("ckeditor_uploader.urls")),
|
||||||
|
]
|
||||||
|
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
||||||
|
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||||
|
)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from django.core.wsgi import get_wsgi_application
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
WSGI config for ckeditor_demo project.
|
||||||
|
|
||||||
|
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ckeditor_demo.settings")
|
||||||
|
|
||||||
|
application = get_wsgi_application()
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
|
|
||||||
|
|
||||||
|
if "ckeditor" in settings.INSTALLED_APPS:
|
||||||
|
# Confirm CKEDITOR_UPLOAD_PATH setting has been specified.
|
||||||
|
try:
|
||||||
|
settings.CKEDITOR_UPLOAD_PATH
|
||||||
|
except AttributeError:
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
"django-ckeditor requires \
|
||||||
|
CKEDITOR_UPLOAD_PATH setting. This setting specifies an \
|
||||||
|
relative path to your ckeditor media upload directory. Make \
|
||||||
|
sure you have write permissions for the path, i.e.: \
|
||||||
|
CKEDITOR_UPLOAD_PATH = 'content/ckeditor/' which \
|
||||||
|
will be added to SITE_MEDIA/MEDIA_ROOT where needed by storage engine."
|
||||||
|
)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import warnings
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.utils.module_loading import import_string
|
||||||
|
|
||||||
|
from .dummy_backend import DummyBackend
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["get_backend", "DummyBackend", "PillowBackend"]
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .pillow_backend import PillowBackend
|
||||||
|
except ImportError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Allow for a custom image backend defined in settings.
|
||||||
|
def get_backend():
|
||||||
|
backend_path = getattr(
|
||||||
|
settings, "CKEDITOR_IMAGE_BACKEND", "ckeditor_uploader.backends.DummyBackend"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Honour old registry keys while emitting warnings
|
||||||
|
if backend_path is None:
|
||||||
|
backend_path = "ckeditor_uploader.backends.DummyBackend"
|
||||||
|
warnings.warn(
|
||||||
|
"CKEDITOR_IMAGE_BACKEND now uses a fully qualified path to the backend class."
|
||||||
|
" None should be changed to 'ckeditor_uploader.backends.DummyBackend'",
|
||||||
|
PendingDeprecationWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
elif backend_path == "pillow":
|
||||||
|
backend_path = "ckeditor_uploader.backends.PillowBackend"
|
||||||
|
warnings.warn(
|
||||||
|
"CKEDITOR_IMAGE_BACKEND now uses a fully qualified path to the backend class."
|
||||||
|
" 'pillow' should be changed to 'ckeditor_uploader.backends.PillowBackend'",
|
||||||
|
PendingDeprecationWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
return import_string(backend_path)
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
from django.utils.functional import cached_property
|
||||||
|
|
||||||
|
from ckeditor_uploader import utils
|
||||||
|
|
||||||
|
|
||||||
|
class DummyBackend:
|
||||||
|
def __init__(self, storage_engine, file_object):
|
||||||
|
self.file_object = file_object
|
||||||
|
self.storage_engine = storage_engine
|
||||||
|
|
||||||
|
def save_as(self, filepath):
|
||||||
|
return self.storage_engine.save(filepath, self.file_object)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def is_image(self):
|
||||||
|
return utils.is_valid_image_extension(self.file_object.name)
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
import os
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.utils.functional import cached_property
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from ckeditor_uploader import utils
|
||||||
|
|
||||||
|
|
||||||
|
THUMBNAIL_SIZE = getattr(settings, "CKEDITOR_THUMBNAIL_SIZE", (75, 75))
|
||||||
|
|
||||||
|
|
||||||
|
class PillowBackend:
|
||||||
|
def __init__(self, storage_engine, file_object):
|
||||||
|
self.file_object = file_object
|
||||||
|
self.storage_engine = storage_engine
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def is_image(self):
|
||||||
|
try:
|
||||||
|
Image.open(
|
||||||
|
BytesIO(self.file_object.read())
|
||||||
|
).verify() # verify closes the file
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.file_object.seek(0)
|
||||||
|
|
||||||
|
def _compress_image(self, image):
|
||||||
|
quality = getattr(settings, "CKEDITOR_IMAGE_QUALITY", 75)
|
||||||
|
image = image.resize(image.size, Image.ANTIALIAS).convert("RGB")
|
||||||
|
image_tmp = BytesIO()
|
||||||
|
image.save(image_tmp, format="JPEG", quality=quality, optimize=True)
|
||||||
|
return image_tmp
|
||||||
|
|
||||||
|
def save_as(self, filepath):
|
||||||
|
if not self.is_image:
|
||||||
|
saved_path = self.storage_engine.save(filepath, self.file_object)
|
||||||
|
return saved_path
|
||||||
|
|
||||||
|
image = Image.open(self.file_object)
|
||||||
|
|
||||||
|
should_compress = getattr(settings, "CKEDITOR_FORCE_JPEG_COMPRESSION", False)
|
||||||
|
is_animated = hasattr(image, "is_animated") and image.is_animated
|
||||||
|
if should_compress and not is_animated:
|
||||||
|
file_object = self._compress_image(image)
|
||||||
|
filepath = f"{os.path.splitext(filepath)[0]}.jpg"
|
||||||
|
saved_path = self.storage_engine.save(filepath, file_object)
|
||||||
|
else:
|
||||||
|
file_object = self.file_object
|
||||||
|
saved_path = self.storage_engine.save(filepath, self.file_object)
|
||||||
|
|
||||||
|
if not is_animated:
|
||||||
|
self.create_thumbnail(file_object, saved_path)
|
||||||
|
return saved_path
|
||||||
|
|
||||||
|
def create_thumbnail(self, file_object, file_path):
|
||||||
|
thumbnail_filename = utils.get_thumb_filename(file_path)
|
||||||
|
thumbnail_io = BytesIO()
|
||||||
|
# File object after saving e.g. to S3 can be closed.
|
||||||
|
try:
|
||||||
|
image = Image.open(file_object).convert("RGB")
|
||||||
|
except ValueError:
|
||||||
|
file_object = self.storage_engine.open(file_path)
|
||||||
|
image = Image.open(file_object).convert("RGB")
|
||||||
|
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
|
||||||
|
image.save(thumbnail_io, format="JPEG", optimize=True)
|
||||||
|
return self.storage_engine.save(thumbnail_filename, thumbnail_io)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from ckeditor import fields
|
||||||
|
|
||||||
|
from . import widgets
|
||||||
|
|
||||||
|
|
||||||
|
class RichTextUploadingField(fields.RichTextField):
|
||||||
|
def formfield(self, **kwargs):
|
||||||
|
defaults = {
|
||||||
|
"form_class": RichTextUploadingFormField,
|
||||||
|
}
|
||||||
|
defaults.update(kwargs)
|
||||||
|
return super().formfield(**defaults)
|
||||||
|
|
||||||
|
|
||||||
|
class RichTextUploadingFormField(fields.RichTextFormField):
|
||||||
|
widget = widgets.CKEditorUploadingWidget
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from django import forms
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
|
||||||
|
class SearchForm(forms.Form):
|
||||||
|
q = forms.CharField(label=_("Search files"), required=False)
|
||||||
Whitespace-only changes.
Whitespace-only changes.
+37
@@ -0,0 +1,37 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
from ckeditor_uploader.backends import get_backend
|
||||||
|
from ckeditor_uploader.utils import get_thumb_filename
|
||||||
|
from ckeditor_uploader.views import get_image_files
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""
|
||||||
|
Creates thumbnail files for the CKEditor file image browser.
|
||||||
|
Useful if starting to use django-ckeditor with existing images.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
if getattr(settings, "CKEDITOR_IMAGE_BACKEND", None):
|
||||||
|
backend = get_backend()
|
||||||
|
for image in get_image_files():
|
||||||
|
if not self._thumbnail_exists(image):
|
||||||
|
self.stdout.write("Creating thumbnail for %s" % image)
|
||||||
|
try:
|
||||||
|
backend.create_thumbnail(image)
|
||||||
|
except Exception as e:
|
||||||
|
self.stdout.write(f"Couldn't create thumbnail for {image}: {e}")
|
||||||
|
self.stdout.write("Finished")
|
||||||
|
else:
|
||||||
|
self.stdout.write("No thumbnail backend is enabled")
|
||||||
|
|
||||||
|
def _thumbnail_exists(self, image_path):
|
||||||
|
thumb_path = self._to_absolute_path(get_thumb_filename(image_path))
|
||||||
|
return os.path.isfile(thumb_path)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _to_absolute_path(image_path):
|
||||||
|
return os.path.join(settings.MEDIA_ROOT, image_path)
|
||||||
+178
@@ -0,0 +1,178 @@
|
|||||||
|
{% load static i18n %}
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
|
||||||
|
<title>CKEditor | {% trans "Select an image to embed" %}</title>
|
||||||
|
<link rel="stylesheet" href="{% static "ckeditor/ckeditor_uploader/admin_base.css" %}" type="text/css" />
|
||||||
|
<link rel="stylesheet" href="{% static "ckeditor/galleriffic/css/basic.css" %}" type="text/css" />
|
||||||
|
<link rel="stylesheet" href="{% static "ckeditor/galleriffic/css/galleriffic-2.css" %}" type="text/css" />
|
||||||
|
<script type="text/javascript" src="{% static "ckeditor/galleriffic/js/jquery-1.3.2.js" %}"></script>
|
||||||
|
<script type="text/javascript" src="{% static "ckeditor/galleriffic/js/jquery.galleriffic.js" %}"></script>
|
||||||
|
<script type="text/javascript" src="{% static "ckeditor/galleriffic/js/jquery.opacityrollover.js" %}"></script>
|
||||||
|
<!-- We only want the thunbnails to display when javascript is disabled -->
|
||||||
|
<script type="text/javascript">
|
||||||
|
document.write('<style>.noscript { display: none; }</style>');
|
||||||
|
</script>
|
||||||
|
<style type="text/css">
|
||||||
|
a.thumb { text-align: center; display: block; float: left; width: 75px; height: 75px; word-wrap: break-word; line-height: 1.2em; overflow: hidden; }
|
||||||
|
a.thumb img { display: inline-block; }
|
||||||
|
span.filename { color: #666; font-size: 0.95em; }
|
||||||
|
#container { min-width: 880px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="page">
|
||||||
|
<div id="container" style="width: 880px">
|
||||||
|
{% if files %}
|
||||||
|
<h2>{% trans "Browse for the image you want, then click 'Embed Image' to continue..." %}</h2>
|
||||||
|
{% else %}
|
||||||
|
<h2>{% trans "No images found. Upload images using the 'Image Button' dialog's 'Upload' tab." %}</h2>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- Start Advanced Gallery Html Containers -->
|
||||||
|
<div id="gallery" class="content">
|
||||||
|
<div class="slideshow-container">
|
||||||
|
<div id="loading" class="loader"></div>
|
||||||
|
<div id="slideshow" class="slideshow"></div>
|
||||||
|
</div>
|
||||||
|
<div id="caption" class="caption-container"></div>
|
||||||
|
</div>
|
||||||
|
<div id="search">
|
||||||
|
<form action="" method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form }}
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div id="thumbs" class="navigation">
|
||||||
|
<ul class="thumbs noscript">
|
||||||
|
{% if show_dirs %}
|
||||||
|
{% for dir in dirs %}
|
||||||
|
<li>{% trans "Images in: " %}{{ dir }}</li>
|
||||||
|
{% for file in files %}
|
||||||
|
{% if dir in file.src %}
|
||||||
|
<li>
|
||||||
|
<a class="thumb" href="{% if file.is_image %}{{ file.src }}{% else %}{{ file.thumb }}{% endif %}">
|
||||||
|
<img src="{{ file.thumb }}" style="max-width: 75px;"/>
|
||||||
|
{% if file.visible_filename %}
|
||||||
|
<span class="filename">{{ file.visible_filename }}</span>
|
||||||
|
{% endif %}
|
||||||
|
</a>
|
||||||
|
<div class="caption">
|
||||||
|
<div class="submit-row">
|
||||||
|
<input href="{{ file.src }}" class="default embed" type="submit" name="_embed" value="{% trans "Embed Image" %}" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %} <!-- for file in files -->
|
||||||
|
{% endfor %} <!-- for dir in dirs -->
|
||||||
|
{% else %}
|
||||||
|
{% for file in files %}
|
||||||
|
<li>
|
||||||
|
<a class="thumb" href="{% if file.is_image %}{{ file.src }}{% else %}{{ file.thumb }}{% endif %}">
|
||||||
|
<img src="{{ file.thumb }}" style="max-width: 75px;"/>
|
||||||
|
{% if file.visible_filename %}
|
||||||
|
<span class="filename">{{ file.visible_filename }}</span>
|
||||||
|
{% endif %}
|
||||||
|
</a>
|
||||||
|
<div class="caption">
|
||||||
|
<div class="submit-row">
|
||||||
|
<input href="{{ file.src }}" class="default embed" type="submit" name="_embed" value="{% trans "Embed Image" %}" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
{% endfor %} <!-- for file in files -->
|
||||||
|
{% endif %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div style="clear: both;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script type="text/javascript">
|
||||||
|
// helper functions
|
||||||
|
function getUrlParam(paramName) {
|
||||||
|
var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i') ;
|
||||||
|
var match = window.location.search.match(reParam) ;
|
||||||
|
|
||||||
|
return (match && match.length > 1) ? match[1] : '' ;
|
||||||
|
}
|
||||||
|
function scale_image() {
|
||||||
|
var max_width = 500;
|
||||||
|
var image = $(".advance-link > img");
|
||||||
|
var image_width = image.width();
|
||||||
|
if (image_width > max_width) {
|
||||||
|
var aspect = image.height() / image_width;
|
||||||
|
var image_height = max_width * aspect;
|
||||||
|
image.width(max_width);
|
||||||
|
image.height(image_height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// embedder
|
||||||
|
$('.embed').live('click', function() {
|
||||||
|
var funcNum = getUrlParam('CKEditorFuncNum');
|
||||||
|
var fileUrl = $(this).attr('href');
|
||||||
|
window.opener.CKEDITOR.tools.callFunction(funcNum, fileUrl);
|
||||||
|
window.close();
|
||||||
|
});
|
||||||
|
// galleriffic
|
||||||
|
jQuery(document).ready(function($) {
|
||||||
|
// We only want these styles applied when javascript is enabled
|
||||||
|
$('div.navigation').css({'width' : '300px', 'float' : 'left'});
|
||||||
|
$('div.content').css('display', 'block');
|
||||||
|
// Initially set opacity on thumbs and add
|
||||||
|
// additional styling for hover effect on thumbs
|
||||||
|
var onMouseOutOpacity = 0.67;
|
||||||
|
$('#thumbs ul.thumbs li').opacityrollover({
|
||||||
|
mouseOutOpacity: onMouseOutOpacity,
|
||||||
|
mouseOverOpacity: 1.0,
|
||||||
|
fadeSpeed: 'fast',
|
||||||
|
exemptionSelector: '.selected'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initialize Advanced Galleriffic Gallery
|
||||||
|
var gallery = $('#thumbs').galleriffic({
|
||||||
|
delay: 2500,
|
||||||
|
numThumbs: 15,
|
||||||
|
preloadAhead: 10,
|
||||||
|
enableTopPager: true,
|
||||||
|
enableBottomPager: true,
|
||||||
|
maxPagesToShow: 7,
|
||||||
|
imageContainerSel: '#slideshow',
|
||||||
|
controlsContainerSel: '#controls',
|
||||||
|
captionContainerSel: '#caption',
|
||||||
|
loadingContainerSel: '#loading',
|
||||||
|
renderSSControls: true,
|
||||||
|
renderNavControls: true,
|
||||||
|
playLinkText: '{% trans "Play Slideshow" %}',
|
||||||
|
pauseLinkText: '{% trans "Pause Slideshow" %}',
|
||||||
|
prevLinkText: '{% trans "‹ Previous Photo" %}',
|
||||||
|
nextLinkText: '{% trans "Next Photo ›" %}',
|
||||||
|
nextPageLinkText: '{% trans "Next ›" %}',
|
||||||
|
prevPageLinkText: '{% trans "‹ Prev" %}',
|
||||||
|
enableHistory: false,
|
||||||
|
autoStart: false,
|
||||||
|
syncTransitions: false,
|
||||||
|
defaultTransitionDuration: 500,
|
||||||
|
onSlideChange: function(prevIndex, nextIndex) {
|
||||||
|
// 'this' refers to the gallery, which is an extension of $('#thumbs')
|
||||||
|
this.find('ul.thumbs').children()
|
||||||
|
.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
|
||||||
|
.eq(nextIndex).fadeTo('fast', 1.0);
|
||||||
|
},
|
||||||
|
onPageTransitionOut: function(callback) {
|
||||||
|
this.fadeTo('fast', 0.0, callback);
|
||||||
|
},
|
||||||
|
onPageTransitionIn: function() {
|
||||||
|
this.fadeTo('fast', 1.0);
|
||||||
|
},
|
||||||
|
onTransitionIn: function(newSlide, newCaption, isSync) {
|
||||||
|
scale_image();
|
||||||
|
newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
|
||||||
|
if (newCaption)
|
||||||
|
newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from django.contrib.admin.views.decorators import staff_member_required
|
||||||
|
from django.urls import re_path
|
||||||
|
from django.views.decorators.cache import never_cache
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
re_path(r"^upload/", staff_member_required(views.upload), name="ckeditor_upload"),
|
||||||
|
re_path(
|
||||||
|
r"^browse/",
|
||||||
|
never_cache(staff_member_required(views.browse)),
|
||||||
|
name="ckeditor_browse",
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import os.path
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import string
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.template.defaultfilters import slugify
|
||||||
|
from django.utils.encoding import force_str
|
||||||
|
from django.utils.module_loading import import_string
|
||||||
|
|
||||||
|
|
||||||
|
# Non-image file icons, matched from top to bottom
|
||||||
|
|
||||||
|
fileicons_path = "{}/file-icons/".format(
|
||||||
|
getattr(settings, "CKEDITOR_FILEICONS_PATH", "/static/ckeditor")
|
||||||
|
)
|
||||||
|
# This allows adding or overriding the default icons used by Gallerific by getting an additional two-tuple list from
|
||||||
|
# the project settings. If it does not exist, it is ignored. If the same file extension exists twice, the settings
|
||||||
|
# file version is used instead of the default.
|
||||||
|
override_icons = getattr(settings, "CKEDITOR_FILEICONS", [])
|
||||||
|
ckeditor_icons = [
|
||||||
|
(r"\.pdf$", fileicons_path + "pdf.png"),
|
||||||
|
(r"\.doc$|\.docx$|\.odt$", fileicons_path + "doc.png"),
|
||||||
|
(r"\.txt$", fileicons_path + "txt.png"),
|
||||||
|
(r"\.ppt$", fileicons_path + "ppt.png"),
|
||||||
|
(r"\.xls$", fileicons_path + "xls.png"),
|
||||||
|
(".*", fileicons_path + "file.png"), # Default
|
||||||
|
]
|
||||||
|
CKEDITOR_FILEICONS = override_icons + ckeditor_icons
|
||||||
|
|
||||||
|
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif"}
|
||||||
|
|
||||||
|
|
||||||
|
# Allow for a custom storage backend defined in settings.
|
||||||
|
def get_storage_class():
|
||||||
|
return import_string(
|
||||||
|
getattr(
|
||||||
|
settings,
|
||||||
|
"CKEDITOR_STORAGE_BACKEND",
|
||||||
|
"django.core.files.storage.DefaultStorage",
|
||||||
|
)
|
||||||
|
)()
|
||||||
|
|
||||||
|
|
||||||
|
storage = get_storage_class()
|
||||||
|
|
||||||
|
|
||||||
|
def slugify_filename(filename):
|
||||||
|
"""Slugify filename"""
|
||||||
|
name, ext = os.path.splitext(filename)
|
||||||
|
slugified = get_slugified_name(name)
|
||||||
|
return slugified + ext
|
||||||
|
|
||||||
|
|
||||||
|
def get_slugified_name(filename):
|
||||||
|
slugified = slugify(filename)
|
||||||
|
return slugified or get_random_string()
|
||||||
|
|
||||||
|
|
||||||
|
def get_random_string():
|
||||||
|
return "".join(random.sample(string.ascii_lowercase * 6, 6))
|
||||||
|
|
||||||
|
|
||||||
|
def get_icon_filename(file_name):
|
||||||
|
"""
|
||||||
|
Return the path to a file icon that matches the file name.
|
||||||
|
"""
|
||||||
|
for regex, iconpath in CKEDITOR_FILEICONS:
|
||||||
|
if re.search(regex, file_name, re.I):
|
||||||
|
return iconpath
|
||||||
|
|
||||||
|
|
||||||
|
def get_thumb_filename(file_name):
|
||||||
|
"""
|
||||||
|
Generate thumb filename by adding _thumb to end of
|
||||||
|
filename before . (if present)
|
||||||
|
"""
|
||||||
|
return force_str("{0}_thumb{1}").format(*os.path.splitext(file_name))
|
||||||
|
|
||||||
|
|
||||||
|
def get_media_url(path):
|
||||||
|
"""
|
||||||
|
Determine system file's media URL.
|
||||||
|
"""
|
||||||
|
return storage.url(path)
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_image_extension(file_path):
|
||||||
|
extension = os.path.splitext(file_path.lower())[1]
|
||||||
|
return extension in IMAGE_EXTENSIONS
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import inspect
|
||||||
|
import os
|
||||||
|
import warnings
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.http import HttpResponse, JsonResponse
|
||||||
|
from django.shortcuts import render
|
||||||
|
from django.utils.html import escape
|
||||||
|
from django.utils.module_loading import import_string
|
||||||
|
from django.views import generic
|
||||||
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
|
||||||
|
from ckeditor_uploader import utils
|
||||||
|
from ckeditor_uploader.backends import get_backend
|
||||||
|
from ckeditor_uploader.forms import SearchForm
|
||||||
|
from ckeditor_uploader.utils import storage
|
||||||
|
|
||||||
|
from .utils import is_valid_image_extension
|
||||||
|
|
||||||
|
|
||||||
|
def _get_user_path(user):
|
||||||
|
user_path = ""
|
||||||
|
|
||||||
|
# If CKEDITOR_RESTRICT_BY_USER is True upload file to user specific path.
|
||||||
|
RESTRICT_BY_USER = getattr(settings, "CKEDITOR_RESTRICT_BY_USER", False)
|
||||||
|
if RESTRICT_BY_USER:
|
||||||
|
try:
|
||||||
|
user_prop = getattr(user, RESTRICT_BY_USER)
|
||||||
|
except (AttributeError, TypeError):
|
||||||
|
user_prop = getattr(user, "get_username")
|
||||||
|
|
||||||
|
if callable(user_prop):
|
||||||
|
user_path = user_prop()
|
||||||
|
else:
|
||||||
|
user_path = user_prop
|
||||||
|
|
||||||
|
return str(user_path)
|
||||||
|
|
||||||
|
|
||||||
|
def get_upload_filename(upload_name, request):
|
||||||
|
user_path = _get_user_path(request.user)
|
||||||
|
|
||||||
|
# Generate date based path to put uploaded file.
|
||||||
|
# If CKEDITOR_RESTRICT_BY_DATE is True upload file to date specific path.
|
||||||
|
if getattr(settings, "CKEDITOR_RESTRICT_BY_DATE", True):
|
||||||
|
date_path = datetime.now().strftime("%Y/%m/%d")
|
||||||
|
else:
|
||||||
|
date_path = ""
|
||||||
|
|
||||||
|
# Complete upload path (upload_path + date_path).
|
||||||
|
upload_path = os.path.join(settings.CKEDITOR_UPLOAD_PATH, user_path, date_path)
|
||||||
|
|
||||||
|
if getattr(settings, "CKEDITOR_UPLOAD_SLUGIFY_FILENAME", True) and not hasattr(
|
||||||
|
settings, "CKEDITOR_FILENAME_GENERATOR"
|
||||||
|
):
|
||||||
|
upload_name = utils.slugify_filename(upload_name)
|
||||||
|
|
||||||
|
if hasattr(settings, "CKEDITOR_FILENAME_GENERATOR"):
|
||||||
|
generator = import_string(settings.CKEDITOR_FILENAME_GENERATOR)
|
||||||
|
# Does the generator accept a request argument?
|
||||||
|
try:
|
||||||
|
inspect.signature(generator).bind(upload_name, request)
|
||||||
|
except TypeError:
|
||||||
|
# Does the generator accept only an upload_name argument?
|
||||||
|
try:
|
||||||
|
inspect.signature(generator).bind(upload_name)
|
||||||
|
except TypeError:
|
||||||
|
warnings.warn(
|
||||||
|
"Update %s() to accept the arguments `filename, request`."
|
||||||
|
% settings.CKEDITOR_FILENAME_GENERATOR
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
warnings.warn(
|
||||||
|
"Update %s() to accept a second `request` argument."
|
||||||
|
% settings.CKEDITOR_FILENAME_GENERATOR,
|
||||||
|
PendingDeprecationWarning,
|
||||||
|
)
|
||||||
|
upload_name = generator(upload_name)
|
||||||
|
else:
|
||||||
|
upload_name = generator(upload_name, request)
|
||||||
|
|
||||||
|
return storage.get_available_name(os.path.join(upload_path, upload_name))
|
||||||
|
|
||||||
|
|
||||||
|
class ImageUploadView(generic.View):
|
||||||
|
http_method_names = ["post"]
|
||||||
|
|
||||||
|
def post(self, request, **kwargs):
|
||||||
|
"""
|
||||||
|
Uploads a file and send back its URL to CKEditor.
|
||||||
|
"""
|
||||||
|
uploaded_file = request.FILES["upload"]
|
||||||
|
|
||||||
|
backend = get_backend()
|
||||||
|
|
||||||
|
ck_func_num = request.GET.get("CKEditorFuncNum")
|
||||||
|
if ck_func_num:
|
||||||
|
ck_func_num = escape(ck_func_num)
|
||||||
|
|
||||||
|
filewrapper = backend(storage, uploaded_file)
|
||||||
|
allow_nonimages = getattr(settings, "CKEDITOR_ALLOW_NONIMAGE_FILES", True)
|
||||||
|
# Throws an error when an non-image file are uploaded.
|
||||||
|
if not filewrapper.is_image and not allow_nonimages:
|
||||||
|
return HttpResponse(
|
||||||
|
"""
|
||||||
|
<script type='text/javascript'>
|
||||||
|
window.parent.CKEDITOR.tools.callFunction({}, '', 'Invalid file type.');
|
||||||
|
</script>""".format(
|
||||||
|
ck_func_num
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
filepath = get_upload_filename(uploaded_file.name, request)
|
||||||
|
|
||||||
|
saved_path = filewrapper.save_as(filepath)
|
||||||
|
|
||||||
|
url = utils.get_media_url(saved_path)
|
||||||
|
|
||||||
|
if ck_func_num:
|
||||||
|
# Respond with Javascript sending ckeditor upload url.
|
||||||
|
return HttpResponse(
|
||||||
|
"""
|
||||||
|
<script type='text/javascript'>
|
||||||
|
window.parent.CKEDITOR.tools.callFunction({}, '{}');
|
||||||
|
</script>""".format(
|
||||||
|
ck_func_num, url
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
_, filename = os.path.split(saved_path)
|
||||||
|
retdata = {"url": url, "uploaded": "1", "fileName": filename}
|
||||||
|
return JsonResponse(retdata)
|
||||||
|
|
||||||
|
|
||||||
|
upload = csrf_exempt(ImageUploadView.as_view())
|
||||||
|
|
||||||
|
|
||||||
|
def get_image_files(user=None, path=""):
|
||||||
|
"""
|
||||||
|
Recursively walks all dirs under upload dir and generates a list of
|
||||||
|
full paths for each file found.
|
||||||
|
"""
|
||||||
|
# If a user is provided and CKEDITOR_RESTRICT_BY_USER is True,
|
||||||
|
# limit images to user specific path, but not for superusers.
|
||||||
|
STORAGE_DIRECTORIES = 0
|
||||||
|
STORAGE_FILES = 1
|
||||||
|
|
||||||
|
# allow browsing from anywhere if user is superuser
|
||||||
|
# otherwise use the user path
|
||||||
|
if user and not user.is_superuser:
|
||||||
|
user_path = _get_user_path(user)
|
||||||
|
else:
|
||||||
|
user_path = ""
|
||||||
|
|
||||||
|
browse_path = os.path.join(settings.CKEDITOR_UPLOAD_PATH, user_path, path)
|
||||||
|
|
||||||
|
try:
|
||||||
|
storage_list = storage.listdir(browse_path)
|
||||||
|
except NotImplementedError:
|
||||||
|
return
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
|
||||||
|
for filename in storage_list[STORAGE_FILES]:
|
||||||
|
if os.path.splitext(filename)[0].endswith("_thumb") or os.path.basename(
|
||||||
|
filename
|
||||||
|
).startswith("."):
|
||||||
|
continue
|
||||||
|
filename = os.path.join(browse_path, filename)
|
||||||
|
yield filename
|
||||||
|
|
||||||
|
for directory in storage_list[STORAGE_DIRECTORIES]:
|
||||||
|
if directory.startswith("."):
|
||||||
|
continue
|
||||||
|
directory_path = os.path.join(path, directory)
|
||||||
|
yield from get_image_files(user=user, path=directory_path)
|
||||||
|
|
||||||
|
|
||||||
|
def get_files_browse_urls(user=None):
|
||||||
|
"""
|
||||||
|
Recursively walks all dirs under upload dir and generates a list of
|
||||||
|
thumbnail and full image URL's for each file found.
|
||||||
|
"""
|
||||||
|
files = []
|
||||||
|
for filename in get_image_files(user=user):
|
||||||
|
src = utils.get_media_url(filename)
|
||||||
|
if getattr(settings, "CKEDITOR_IMAGE_BACKEND", None):
|
||||||
|
if is_valid_image_extension(src):
|
||||||
|
thumb = utils.get_media_url(utils.get_thumb_filename(filename))
|
||||||
|
else:
|
||||||
|
thumb = utils.get_icon_filename(filename)
|
||||||
|
visible_filename = os.path.split(filename)[1]
|
||||||
|
if len(visible_filename) > 20:
|
||||||
|
visible_filename = visible_filename[0:19] + "..."
|
||||||
|
else:
|
||||||
|
thumb = src
|
||||||
|
visible_filename = os.path.split(filename)[1]
|
||||||
|
files.append(
|
||||||
|
{
|
||||||
|
"thumb": thumb,
|
||||||
|
"src": src,
|
||||||
|
"is_image": is_valid_image_extension(src),
|
||||||
|
"visible_filename": visible_filename,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def browse(request):
|
||||||
|
files = get_files_browse_urls(request.user)
|
||||||
|
if request.method == "POST":
|
||||||
|
form = SearchForm(request.POST)
|
||||||
|
if form.is_valid():
|
||||||
|
query = form.cleaned_data.get("q", "").lower()
|
||||||
|
files = list(
|
||||||
|
filter(lambda d: query in d["visible_filename"].lower(), files)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
form = SearchForm()
|
||||||
|
|
||||||
|
show_dirs = getattr(settings, "CKEDITOR_BROWSE_SHOW_DIRS", False)
|
||||||
|
dir_list = sorted({os.path.dirname(f["src"]) for f in files}, reverse=True)
|
||||||
|
|
||||||
|
# Ensures there are no objects created from Thumbs.db files - ran across
|
||||||
|
# this problem while developing on Windows
|
||||||
|
if os.name == "nt":
|
||||||
|
files = [f for f in files if os.path.basename(f["src"]) != "Thumbs.db"]
|
||||||
|
|
||||||
|
context = {"show_dirs": show_dirs, "dirs": dir_list, "files": files, "form": form}
|
||||||
|
return render(request, "ckeditor/browse.html", context)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from ckeditor import widgets
|
||||||
|
|
||||||
|
|
||||||
|
class CKEditorUploadingWidget(widgets.CKEditorWidget):
|
||||||
|
def _set_config(self):
|
||||||
|
if "filebrowserUploadUrl" not in self.config:
|
||||||
|
self.config.setdefault("filebrowserUploadUrl", reverse("ckeditor_upload"))
|
||||||
|
if "filebrowserBrowseUrl" not in self.config:
|
||||||
|
self.config.setdefault("filebrowserBrowseUrl", reverse("ckeditor_browse"))
|
||||||
|
super()._set_config()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
__version__ = "1.14.0"
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
class KeepContext:
|
||||||
|
"""
|
||||||
|
Context manager that receives a `django.template.Context` instance and a list of keys
|
||||||
|
|
||||||
|
Once the context manager is exited, it removes `keys` from the context, to avoid
|
||||||
|
side effects in later layout objects that may use the same context variables.
|
||||||
|
|
||||||
|
Layout objects should use `extra_context` to introduce context variables, never
|
||||||
|
touch context object themselves, that could introduce side effects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, context, keys):
|
||||||
|
self.context = context
|
||||||
|
self.keys = keys
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __exit__(self, type, value, traceback):
|
||||||
|
for key in list(self.keys):
|
||||||
|
if key in self.context:
|
||||||
|
del self.context[key]
|
||||||
@@ -0,0 +1,504 @@
|
|||||||
|
from random import randint
|
||||||
|
|
||||||
|
from django.template import Template
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
from django.utils.text import slugify
|
||||||
|
|
||||||
|
from .layout import Div, Field, LayoutObject, TemplateNameMixin
|
||||||
|
from .utils import TEMPLATE_PACK, flatatt, render_field
|
||||||
|
|
||||||
|
|
||||||
|
class PrependedAppendedText(Field):
|
||||||
|
template = "%s/layout/prepended_appended_text.html"
|
||||||
|
|
||||||
|
def __init__(self, field, prepended_text=None, appended_text=None, input_size=None, *args, **kwargs):
|
||||||
|
self.field = field
|
||||||
|
self.appended_text = appended_text
|
||||||
|
self.prepended_text = prepended_text
|
||||||
|
if "active" in kwargs:
|
||||||
|
self.active = kwargs.pop("active")
|
||||||
|
|
||||||
|
self.input_size = input_size
|
||||||
|
css_class = kwargs.get("css_class", "")
|
||||||
|
|
||||||
|
# Bootstrap 3
|
||||||
|
if "input-lg" in css_class:
|
||||||
|
self.input_size = "input-lg"
|
||||||
|
if "input-sm" in css_class:
|
||||||
|
self.input_size = "input-sm"
|
||||||
|
|
||||||
|
super().__init__(field, *args, **kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
|
||||||
|
extra_context = extra_context.copy() if extra_context is not None else {}
|
||||||
|
extra_context.update(
|
||||||
|
{
|
||||||
|
"crispy_appended_text": self.appended_text,
|
||||||
|
"crispy_prepended_text": self.prepended_text,
|
||||||
|
"input_size": self.input_size,
|
||||||
|
"active": getattr(self, "active", False),
|
||||||
|
"wrapper_class": self.wrapper_class,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
return render_field(
|
||||||
|
self.field,
|
||||||
|
form,
|
||||||
|
form_style,
|
||||||
|
context,
|
||||||
|
template=template,
|
||||||
|
attrs=self.attrs,
|
||||||
|
template_pack=template_pack,
|
||||||
|
extra_context=extra_context,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AppendedText(PrependedAppendedText):
|
||||||
|
def __init__(self, field, text, *args, **kwargs):
|
||||||
|
kwargs.pop("appended_text", None)
|
||||||
|
kwargs.pop("prepended_text", None)
|
||||||
|
self.text = text
|
||||||
|
super().__init__(field, appended_text=text, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class PrependedText(PrependedAppendedText):
|
||||||
|
def __init__(self, field, text, *args, **kwargs):
|
||||||
|
kwargs.pop("appended_text", None)
|
||||||
|
kwargs.pop("prepended_text", None)
|
||||||
|
self.text = text
|
||||||
|
super().__init__(field, prepended_text=text, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class FormActions(LayoutObject):
|
||||||
|
"""
|
||||||
|
Bootstrap layout object. It wraps fields in a <div class="form-actions">
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
FormActions(
|
||||||
|
HTML(<span style="display: hidden;">Information Saved</span>),
|
||||||
|
Submit('Save', 'Save', css_class='btn-primary')
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/formactions.html"
|
||||||
|
|
||||||
|
def __init__(self, *fields, **kwargs):
|
||||||
|
self.fields = list(fields)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.attrs = kwargs
|
||||||
|
if "css_class" in self.attrs:
|
||||||
|
self.attrs["class"] = self.attrs.pop("css_class")
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
html = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"formactions": self, "fields_output": html})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
def flat_attrs(self):
|
||||||
|
return flatatt(self.attrs)
|
||||||
|
|
||||||
|
|
||||||
|
class InlineCheckboxes(Field):
|
||||||
|
"""
|
||||||
|
Layout object for rendering checkboxes inline::
|
||||||
|
|
||||||
|
InlineCheckboxes('field_name')
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/checkboxselectmultiple_inline.html"
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
return super().render(
|
||||||
|
form, form_style, context, template_pack=template_pack, extra_context={"inline_class": "inline"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class InlineRadios(Field):
|
||||||
|
"""
|
||||||
|
Layout object for rendering radiobuttons inline::
|
||||||
|
|
||||||
|
InlineRadios('field_name')
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/radioselect_inline.html"
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
return super().render(
|
||||||
|
form, form_style, context, template_pack=template_pack, extra_context={"inline_class": "inline"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FieldWithButtons(Div):
|
||||||
|
"""
|
||||||
|
A layout object for rendering a single field with any number of buttons.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
fields : str or LayoutObject
|
||||||
|
The first positional argument is the field. This can be either the
|
||||||
|
name of the field as a string or an instance of `Field`. Following
|
||||||
|
arguments will be rendered as buttons.
|
||||||
|
input_size : str
|
||||||
|
Additional CSS class to change the size of the input. e.g.
|
||||||
|
"input-group-sm".
|
||||||
|
kwargs
|
||||||
|
Additional kwargs to be passed to the parent `Div` Layout Object.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
FieldWithButtons(
|
||||||
|
Field("password1", css_class="span4"),
|
||||||
|
StrictButton("Go!", css_id="go-button"),
|
||||||
|
input_size="input-group-sm",
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/field_with_buttons.html"
|
||||||
|
field_template = "%s/field.html"
|
||||||
|
|
||||||
|
def __init__(self, *fields, input_size=None, **kwargs):
|
||||||
|
self.input_size = input_size
|
||||||
|
super().__init__(*fields, **kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
|
||||||
|
# We first render the buttons
|
||||||
|
field_template = self.field_template % template_pack
|
||||||
|
buttons = "".join(
|
||||||
|
render_field(
|
||||||
|
field,
|
||||||
|
form,
|
||||||
|
form_style,
|
||||||
|
context,
|
||||||
|
field_template,
|
||||||
|
layout_object=self,
|
||||||
|
template_pack=template_pack,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
for field in self.fields[1:]
|
||||||
|
)
|
||||||
|
|
||||||
|
extra_context = {"div": self, "buttons": buttons}
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
|
||||||
|
if isinstance(self.fields[0], Field):
|
||||||
|
# FieldWithButtons(Field('field_name'), StrictButton("go"))
|
||||||
|
# We render the field passing its name and attributes
|
||||||
|
return render_field(
|
||||||
|
self.fields[0][0],
|
||||||
|
form,
|
||||||
|
form_style,
|
||||||
|
context,
|
||||||
|
template,
|
||||||
|
attrs=self.fields[0].attrs,
|
||||||
|
template_pack=template_pack,
|
||||||
|
extra_context=extra_context,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return render_field(
|
||||||
|
self.fields[0], form, form_style, context, template, extra_context=extra_context, **kwargs
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class StrictButton(TemplateNameMixin):
|
||||||
|
"""
|
||||||
|
Layout object for rendering an HTML button::
|
||||||
|
|
||||||
|
Button("button content", css_class="extra")
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/button.html"
|
||||||
|
field_classes = "btn"
|
||||||
|
|
||||||
|
def __init__(self, content, **kwargs):
|
||||||
|
self.content = content
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
|
||||||
|
kwargs.setdefault("type", "button")
|
||||||
|
|
||||||
|
# We turn css_id and css_class into id and class
|
||||||
|
if "css_id" in kwargs:
|
||||||
|
kwargs["id"] = kwargs.pop("css_id")
|
||||||
|
kwargs["class"] = self.field_classes
|
||||||
|
if "css_class" in kwargs:
|
||||||
|
kwargs["class"] += " %s" % kwargs.pop("css_class")
|
||||||
|
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
self.content = Template(str(self.content)).render(context)
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"button": self})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class Container(Div):
|
||||||
|
"""
|
||||||
|
Base class used for `Tab` and `AccordionGroup`, represents a basic container concept
|
||||||
|
"""
|
||||||
|
|
||||||
|
css_class = ""
|
||||||
|
|
||||||
|
def __init__(self, name, *fields, **kwargs):
|
||||||
|
super().__init__(*fields, **kwargs)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.name = name
|
||||||
|
self._active_originally_included = "active" in kwargs
|
||||||
|
self.active = kwargs.pop("active", False)
|
||||||
|
if not self.css_id:
|
||||||
|
self.css_id = slugify(self.name, allow_unicode=True)
|
||||||
|
|
||||||
|
def __contains__(self, field_name):
|
||||||
|
"""
|
||||||
|
check if field_name is contained within tab.
|
||||||
|
"""
|
||||||
|
return field_name in map(lambda pointer: pointer[1], self.get_field_names())
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
if self.active:
|
||||||
|
if "active" not in self.css_class:
|
||||||
|
self.css_class += " active"
|
||||||
|
else:
|
||||||
|
self.css_class = self.css_class.replace("active", "")
|
||||||
|
return super().render(form, form_style, context, template_pack)
|
||||||
|
|
||||||
|
|
||||||
|
class ContainerHolder(Div):
|
||||||
|
"""
|
||||||
|
Base class used for `TabHolder` and `Accordion`, groups containers
|
||||||
|
"""
|
||||||
|
|
||||||
|
def first_container_with_errors(self, errors):
|
||||||
|
"""
|
||||||
|
Returns the first container with errors, otherwise returns None.
|
||||||
|
"""
|
||||||
|
for tab in self.fields:
|
||||||
|
errors_here = any(error in tab for error in errors)
|
||||||
|
if errors_here:
|
||||||
|
return tab
|
||||||
|
return None
|
||||||
|
|
||||||
|
def open_target_group_for_form(self, form):
|
||||||
|
"""
|
||||||
|
Makes sure that the first group that should be open is open.
|
||||||
|
This is either the first group with errors or the first group
|
||||||
|
in the container, unless that first group was originally set to
|
||||||
|
active=False.
|
||||||
|
"""
|
||||||
|
target = self.first_container_with_errors(form.errors.keys())
|
||||||
|
if target is None:
|
||||||
|
target = self.fields[0]
|
||||||
|
if not getattr(target, "_active_originally_included", None):
|
||||||
|
target.active = True
|
||||||
|
return target
|
||||||
|
|
||||||
|
target.active = True
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
class Tab(Container):
|
||||||
|
"""
|
||||||
|
Tab object. It wraps fields in a div whose default class is "tab-pane" and
|
||||||
|
takes a name as first argument. Example::
|
||||||
|
|
||||||
|
Tab('tab_name', 'form_field_1', 'form_field_2', 'form_field_3')
|
||||||
|
"""
|
||||||
|
|
||||||
|
css_class = "tab-pane"
|
||||||
|
link_template = "%s/layout/tab-link.html"
|
||||||
|
|
||||||
|
def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
"""
|
||||||
|
Render the link for the tab-pane. It must be called after render so css_class is updated
|
||||||
|
with active if needed.
|
||||||
|
"""
|
||||||
|
link_template = self.link_template % template_pack
|
||||||
|
return render_to_string(link_template, {"link": self})
|
||||||
|
|
||||||
|
|
||||||
|
class TabHolder(ContainerHolder):
|
||||||
|
"""
|
||||||
|
TabHolder object. It wraps Tab objects in a container. Requires bootstrap-tab.js::
|
||||||
|
|
||||||
|
TabHolder(
|
||||||
|
Tab('form_field_1', 'form_field_2'),
|
||||||
|
Tab('form_field_3')
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/tab.html"
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
for tab in self.fields:
|
||||||
|
tab.active = False
|
||||||
|
|
||||||
|
# Open the group that should be open.
|
||||||
|
self.open_target_group_for_form(form)
|
||||||
|
content = self.get_rendered_fields(form, form_style, context, template_pack)
|
||||||
|
links = "".join(tab.render_link(template_pack) for tab in self.fields)
|
||||||
|
|
||||||
|
context.update({"tabs": self, "links": links, "content": content})
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class AccordionGroup(Container):
|
||||||
|
"""
|
||||||
|
Accordion Group (pane) object. It wraps given fields inside an accordion
|
||||||
|
tab. It takes accordion tab name as first argument::
|
||||||
|
|
||||||
|
AccordionGroup("group name", "form_field_1", "form_field_2")
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/accordion-group.html"
|
||||||
|
data_parent = "" # accordion parent div id.
|
||||||
|
|
||||||
|
|
||||||
|
class Accordion(ContainerHolder):
|
||||||
|
"""
|
||||||
|
Accordion menu object. It wraps `AccordionGroup` objects in a container::
|
||||||
|
|
||||||
|
Accordion(
|
||||||
|
AccordionGroup("group name", "form_field_1", "form_field_2"),
|
||||||
|
AccordionGroup("another group name", "form_field")
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/accordion.html"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
# Accordion needs to have a unique id
|
||||||
|
if not self.css_id:
|
||||||
|
self.css_id = "-".join(["accordion", str(randint(1000, 9999))])
|
||||||
|
|
||||||
|
# AccordionGroup need to have 'data-parent="#Accordion.id"'
|
||||||
|
for accordion_group in args:
|
||||||
|
accordion_group.data_parent = self.css_id
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
content = ""
|
||||||
|
|
||||||
|
# Open the group that should be open.
|
||||||
|
self.open_target_group_for_form(form)
|
||||||
|
|
||||||
|
for group in self.fields:
|
||||||
|
group.data_parent = self.css_id
|
||||||
|
content += render_field(group, form, form_style, context, template_pack=template_pack, **kwargs)
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"accordion": self, "content": content})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class Alert(Div):
|
||||||
|
"""
|
||||||
|
`Alert` generates markup in the form of an alert dialog
|
||||||
|
|
||||||
|
Alert(content='<strong>Warning!</strong> Best check yo self, you're not looking too good.')
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/alert.html"
|
||||||
|
css_class = "alert"
|
||||||
|
|
||||||
|
def __init__(self, content, dismiss=True, block=False, **kwargs):
|
||||||
|
fields = []
|
||||||
|
if block:
|
||||||
|
self.css_class += " alert-block"
|
||||||
|
Div.__init__(self, *fields, **kwargs)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.content = content
|
||||||
|
self.dismiss = dismiss
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"alert": self, "content": self.content, "dismiss": self.dismiss})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class UneditableField(Field):
|
||||||
|
"""
|
||||||
|
Layout object for rendering fields as uneditable in bootstrap
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
UneditableField('field_name', css_class="input-xlarge")
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/uneditable_input.html"
|
||||||
|
|
||||||
|
def __init__(self, field, *args, **kwargs):
|
||||||
|
self.attrs = {"class": "uneditable-input"}
|
||||||
|
super().__init__(field, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class InlineField(Field):
|
||||||
|
template = "%s/layout/inline_field.html"
|
||||||
|
|
||||||
|
|
||||||
|
class Modal(LayoutObject):
|
||||||
|
"""
|
||||||
|
Boostrap layout object for rendering crispy forms objects inside a bootstrap modal.
|
||||||
|
|
||||||
|
The following attributes can be set:
|
||||||
|
- `css_id`: modal's DOM id
|
||||||
|
- `css_class`: modal's DOM classes
|
||||||
|
- NOTE: "modal" and "fade" are applied by default on the template
|
||||||
|
- `title`: text to display in the modal's header
|
||||||
|
- NOTE: text will be wrapped in a <h5> tag
|
||||||
|
- `title_id`: title's DOM id
|
||||||
|
- `title_class`: titles's DOM classes
|
||||||
|
- NOTE: "modal-title" is applied by default on the template
|
||||||
|
- template
|
||||||
|
The default template which this Layout Object will be rendered
|
||||||
|
with
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
Modal(
|
||||||
|
'field1',
|
||||||
|
Div('field2'),
|
||||||
|
css_id="modal-id-ex",
|
||||||
|
css_class="modal-class-ex,
|
||||||
|
title="This is my modal",
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/modal.html"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*fields,
|
||||||
|
template=None,
|
||||||
|
css_id="modal_id",
|
||||||
|
title="Modal Title",
|
||||||
|
title_id="modal_title_id",
|
||||||
|
css_class="",
|
||||||
|
title_class="",
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
|
||||||
|
self.fields = list(fields)
|
||||||
|
self.template = template or self.template
|
||||||
|
self.css_id = css_id
|
||||||
|
self.css_class = css_class
|
||||||
|
self.title = title
|
||||||
|
self.title_id = title_id
|
||||||
|
self.title_class = title_class
|
||||||
|
|
||||||
|
kwargs = {**kwargs, "tabindex": "-1", "role": "dialog", "aria-labelledby": "%s-label" % self.title_id}
|
||||||
|
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
|
||||||
|
return render_to_string(template, {"modal": self, "fields": fields})
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
class CrispyError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FormHelpersException(CrispyError):
|
||||||
|
"""
|
||||||
|
This is raised when building a form via helpers throws an error.
|
||||||
|
We want to catch form helper errors as soon as possible because
|
||||||
|
debugging templatetags is never fun.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DynamicError(CrispyError):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
from django.urls import NoReverseMatch, reverse
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
|
from crispy_forms.exceptions import FormHelpersException
|
||||||
|
from crispy_forms.layout import Layout
|
||||||
|
from crispy_forms.layout_slice import LayoutSlice
|
||||||
|
from crispy_forms.utils import TEMPLATE_PACK, flatatt, list_difference, render_field
|
||||||
|
|
||||||
|
|
||||||
|
class DynamicLayoutHandler:
|
||||||
|
def _check_layout(self):
|
||||||
|
if self.layout is None:
|
||||||
|
raise FormHelpersException("You need to set a layout in your FormHelper")
|
||||||
|
|
||||||
|
def _check_layout_and_form(self):
|
||||||
|
self._check_layout()
|
||||||
|
if self.form is None:
|
||||||
|
raise FormHelpersException("You need to pass a form instance to your FormHelper")
|
||||||
|
|
||||||
|
def all(self):
|
||||||
|
"""
|
||||||
|
Returns all layout objects of first level of depth
|
||||||
|
"""
|
||||||
|
self._check_layout()
|
||||||
|
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1))
|
||||||
|
|
||||||
|
def filter(self, *LayoutClasses, **kwargs):
|
||||||
|
"""
|
||||||
|
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
|
||||||
|
"""
|
||||||
|
self._check_layout()
|
||||||
|
max_level = kwargs.pop("max_level", 0)
|
||||||
|
greedy = kwargs.pop("greedy", False)
|
||||||
|
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
|
||||||
|
|
||||||
|
return LayoutSlice(self.layout, filtered_layout_objects)
|
||||||
|
|
||||||
|
def filter_by_widget(self, widget_type):
|
||||||
|
"""
|
||||||
|
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
|
||||||
|
"""
|
||||||
|
self._check_layout_and_form()
|
||||||
|
layout_field_names = self.layout.get_field_names()
|
||||||
|
|
||||||
|
# Let's filter all fields with widgets like widget_type
|
||||||
|
filtered_fields = []
|
||||||
|
for pointer in layout_field_names:
|
||||||
|
if isinstance(self.form.fields[pointer[1]].widget, widget_type):
|
||||||
|
filtered_fields.append(pointer)
|
||||||
|
|
||||||
|
return LayoutSlice(self.layout, filtered_fields)
|
||||||
|
|
||||||
|
def exclude_by_widget(self, widget_type):
|
||||||
|
"""
|
||||||
|
Returns a LayoutSlice pointing to fields with widgets NOT matching `widget_type`
|
||||||
|
"""
|
||||||
|
self._check_layout_and_form()
|
||||||
|
layout_field_names = self.layout.get_field_names()
|
||||||
|
|
||||||
|
# Let's exclude all fields with widgets like widget_type
|
||||||
|
filtered_fields = []
|
||||||
|
for pointer in layout_field_names:
|
||||||
|
if not isinstance(self.form.fields[pointer[1]].widget, widget_type):
|
||||||
|
filtered_fields.append(pointer)
|
||||||
|
|
||||||
|
return LayoutSlice(self.layout, filtered_fields)
|
||||||
|
|
||||||
|
def __getitem__(self, key):
|
||||||
|
"""
|
||||||
|
Return a LayoutSlice that makes changes affect the current instance of the layout
|
||||||
|
and not a copy.
|
||||||
|
"""
|
||||||
|
# when key is a string containing the field name
|
||||||
|
if isinstance(key, str):
|
||||||
|
# Django templates access FormHelper attributes using dictionary [] operator
|
||||||
|
# This could be a helper['form_id'] access, not looking for a field
|
||||||
|
if hasattr(self, key):
|
||||||
|
return getattr(self, key)
|
||||||
|
|
||||||
|
self._check_layout()
|
||||||
|
layout_field_names = self.layout.get_field_names()
|
||||||
|
|
||||||
|
filtered_field = []
|
||||||
|
for pointer in layout_field_names:
|
||||||
|
# There can be an empty pointer
|
||||||
|
if len(pointer) == 2 and pointer[1] == key:
|
||||||
|
filtered_field.append(pointer)
|
||||||
|
|
||||||
|
return LayoutSlice(self.layout, filtered_field)
|
||||||
|
|
||||||
|
return LayoutSlice(self.layout, key)
|
||||||
|
|
||||||
|
def __setitem__(self, key, value):
|
||||||
|
self.layout[key] = value
|
||||||
|
|
||||||
|
def __delitem__(self, key):
|
||||||
|
del self.layout.fields[key]
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
if self.layout is not None:
|
||||||
|
return len(self.layout.fields)
|
||||||
|
else:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
class FormHelper(DynamicLayoutHandler):
|
||||||
|
"""
|
||||||
|
This class controls the form rendering behavior of the form passed to
|
||||||
|
the `{% crispy %}` tag. For doing so you will need to set its attributes
|
||||||
|
and pass the corresponding helper object to the tag::
|
||||||
|
|
||||||
|
{% crispy form form.helper %}
|
||||||
|
|
||||||
|
Let's see what attributes you can set and what form behaviors they apply to:
|
||||||
|
|
||||||
|
**form_method**: Specifies form method attribute.
|
||||||
|
You can set it to 'POST' or 'GET'. Defaults to 'POST'
|
||||||
|
|
||||||
|
**form_action**: Applied to the form action attribute:
|
||||||
|
- Can be a named url in your URLconf that can be executed via the `{% url %}` template tag. \
|
||||||
|
Example: 'show_my_profile'. In your URLconf you could have something like::
|
||||||
|
|
||||||
|
path('show/profile/', 'show_my_profile_view', name = 'show_my_profile')
|
||||||
|
|
||||||
|
- It can simply point to a URL '/whatever/blabla/'.
|
||||||
|
|
||||||
|
**form_id**: Generates a form id for dom identification.
|
||||||
|
If no id provided then no id attribute is created on the form.
|
||||||
|
|
||||||
|
**form_class**: String containing separated CSS classes to be applied
|
||||||
|
to form class attribute. The form will always have by default
|
||||||
|
'uniForm' class.
|
||||||
|
|
||||||
|
**form_group_wrapper_class**: String containing separated CSS classes to be applied
|
||||||
|
to each row of inputs.
|
||||||
|
|
||||||
|
**form_tag**: It specifies if <form></form> tags should be rendered when using a Layout.
|
||||||
|
If set to False it renders the form without the <form></form> tags. Defaults to True.
|
||||||
|
|
||||||
|
**form_error_title**: If a form has `non_field_errors` to display, they
|
||||||
|
are rendered in a div. You can set title's div with this attribute.
|
||||||
|
Example: "Oooops!" or "Form Errors"
|
||||||
|
|
||||||
|
**formset_error_title**: If a formset has `non_form_errors` to display, they
|
||||||
|
are rendered in a div. You can set title's div with this attribute.
|
||||||
|
|
||||||
|
**form_style**: Uni-form has two built in different form styles. You can choose
|
||||||
|
your favorite. This can be set to "default" or "inline". Defaults to "default".
|
||||||
|
|
||||||
|
**include_media**: Whether to automatically include form media. Set to False if
|
||||||
|
you want to manually include form media outside the form. Defaults to True.
|
||||||
|
|
||||||
|
Public Methods:
|
||||||
|
|
||||||
|
**add_input(input)**: You can add input buttons using this method. Inputs
|
||||||
|
added using this method will be rendered at the end of the form/formset.
|
||||||
|
|
||||||
|
**add_layout(layout)**: You can add a `Layout` object to `FormHelper`. The Layout
|
||||||
|
specifies in a simple, clean and DRY way how the form fields should be rendered.
|
||||||
|
You can wrap fields, order them, customize pretty much anything in the form.
|
||||||
|
|
||||||
|
Best way to add a helper to a form is adding a property named helper to the form
|
||||||
|
that returns customized `FormHelper` object::
|
||||||
|
|
||||||
|
from crispy_forms.helper import FormHelper
|
||||||
|
from crispy_forms.layout import Submit
|
||||||
|
|
||||||
|
class MyForm(forms.Form):
|
||||||
|
title = forms.CharField(_("Title"))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def helper(self):
|
||||||
|
helper = FormHelper()
|
||||||
|
helper.form_id = 'this-form-rocks'
|
||||||
|
helper.form_class = 'search'
|
||||||
|
helper.add_input(Submit('save', 'save'))
|
||||||
|
[...]
|
||||||
|
return helper
|
||||||
|
|
||||||
|
You can use it in a template doing::
|
||||||
|
|
||||||
|
{% load crispy_forms_tags %}
|
||||||
|
{% crispy form %}
|
||||||
|
"""
|
||||||
|
|
||||||
|
_form_method = "post"
|
||||||
|
_form_action = ""
|
||||||
|
_form_style = "default"
|
||||||
|
form = None
|
||||||
|
form_id = ""
|
||||||
|
form_class = ""
|
||||||
|
form_group_wrapper_class = ""
|
||||||
|
layout = None
|
||||||
|
form_tag = True
|
||||||
|
form_error_title = None
|
||||||
|
formset_error_title = None
|
||||||
|
form_show_errors = True
|
||||||
|
render_unmentioned_fields = False
|
||||||
|
render_hidden_fields = False
|
||||||
|
render_required_fields = False
|
||||||
|
_help_text_inline = False
|
||||||
|
_error_text_inline = True
|
||||||
|
html5_required = False
|
||||||
|
form_show_labels = True
|
||||||
|
template = None
|
||||||
|
field_template = None
|
||||||
|
disable_csrf = False
|
||||||
|
use_custom_control = True
|
||||||
|
label_class = ""
|
||||||
|
field_class = ""
|
||||||
|
include_media = True
|
||||||
|
|
||||||
|
def __init__(self, form=None):
|
||||||
|
self.attrs = {}
|
||||||
|
self.inputs = []
|
||||||
|
|
||||||
|
if form is not None:
|
||||||
|
self.form = form
|
||||||
|
self.layout = self.build_default_layout(form)
|
||||||
|
|
||||||
|
def build_default_layout(self, form):
|
||||||
|
return Layout(*form.fields.keys())
|
||||||
|
|
||||||
|
@property
|
||||||
|
def form_method(self):
|
||||||
|
return self._form_method
|
||||||
|
|
||||||
|
@form_method.setter
|
||||||
|
def form_method(self, method):
|
||||||
|
if method.lower() not in ("get", "post"):
|
||||||
|
raise FormHelpersException(
|
||||||
|
"Only GET and POST are valid in the \
|
||||||
|
form_method helper attribute"
|
||||||
|
)
|
||||||
|
|
||||||
|
self._form_method = method.lower()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def form_action(self):
|
||||||
|
try:
|
||||||
|
return reverse(self._form_action)
|
||||||
|
except NoReverseMatch:
|
||||||
|
return self._form_action
|
||||||
|
|
||||||
|
@form_action.setter
|
||||||
|
def form_action(self, action):
|
||||||
|
self._form_action = action
|
||||||
|
|
||||||
|
@property
|
||||||
|
def form_style(self):
|
||||||
|
if self._form_style == "default":
|
||||||
|
return ""
|
||||||
|
|
||||||
|
if self._form_style == "inline":
|
||||||
|
return "inlineLabels"
|
||||||
|
|
||||||
|
@form_style.setter
|
||||||
|
def form_style(self, style):
|
||||||
|
if style.lower() not in ("default", "inline"):
|
||||||
|
raise FormHelpersException(
|
||||||
|
"Only default and inline are valid in the \
|
||||||
|
form_style helper attribute"
|
||||||
|
)
|
||||||
|
|
||||||
|
self._form_style = style.lower()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def help_text_inline(self):
|
||||||
|
return self._help_text_inline
|
||||||
|
|
||||||
|
@help_text_inline.setter
|
||||||
|
def help_text_inline(self, flag):
|
||||||
|
self._help_text_inline = flag
|
||||||
|
self._error_text_inline = not flag
|
||||||
|
|
||||||
|
@property
|
||||||
|
def error_text_inline(self):
|
||||||
|
return self._error_text_inline
|
||||||
|
|
||||||
|
@error_text_inline.setter
|
||||||
|
def error_text_inline(self, flag):
|
||||||
|
self._error_text_inline = flag
|
||||||
|
self._help_text_inline = not flag
|
||||||
|
|
||||||
|
def add_input(self, input_object):
|
||||||
|
self.inputs.append(input_object)
|
||||||
|
|
||||||
|
def add_layout(self, layout):
|
||||||
|
self.layout = layout
|
||||||
|
|
||||||
|
def render_layout(self, form, context, template_pack=TEMPLATE_PACK):
|
||||||
|
"""
|
||||||
|
Returns safe html of the rendering of the layout
|
||||||
|
"""
|
||||||
|
form.rendered_fields = set()
|
||||||
|
form.crispy_field_template = self.field_template
|
||||||
|
|
||||||
|
# This renders the specified Layout strictly
|
||||||
|
html = self.layout.render(form, self.form_style, context, template_pack=template_pack)
|
||||||
|
|
||||||
|
# Rendering some extra fields if specified
|
||||||
|
if self.render_unmentioned_fields or self.render_hidden_fields or self.render_required_fields:
|
||||||
|
fields = tuple(form.fields.keys())
|
||||||
|
left_fields_to_render = list_difference(fields, form.rendered_fields)
|
||||||
|
for field in left_fields_to_render:
|
||||||
|
if (
|
||||||
|
self.render_unmentioned_fields
|
||||||
|
or (self.render_hidden_fields and form.fields[field].widget.is_hidden)
|
||||||
|
or (self.render_required_fields and form.fields[field].widget.is_required)
|
||||||
|
):
|
||||||
|
html += render_field(field, form, self.form_style, context, template_pack=template_pack)
|
||||||
|
|
||||||
|
return mark_safe(html)
|
||||||
|
|
||||||
|
def get_attributes(self, template_pack=TEMPLATE_PACK): # noqa: C901
|
||||||
|
"""
|
||||||
|
Used by crispy_forms_tags to get helper attributes
|
||||||
|
"""
|
||||||
|
items = {
|
||||||
|
"disable_csrf": self.disable_csrf,
|
||||||
|
"error_text_inline": self.error_text_inline,
|
||||||
|
"field_class": self.field_class,
|
||||||
|
"field_template": self.field_template or "%s/field.html" % template_pack,
|
||||||
|
"form_method": self.form_method.strip(),
|
||||||
|
"form_show_errors": self.form_show_errors,
|
||||||
|
"form_show_labels": self.form_show_labels,
|
||||||
|
"form_style": self.form_style.strip(),
|
||||||
|
"form_tag": self.form_tag,
|
||||||
|
"help_text_inline": self.help_text_inline,
|
||||||
|
"html5_required": self.html5_required,
|
||||||
|
"include_media": self.include_media,
|
||||||
|
"label_class": self.label_class,
|
||||||
|
"use_custom_control": self.use_custom_control,
|
||||||
|
}
|
||||||
|
|
||||||
|
if template_pack == "bootstrap4":
|
||||||
|
if "form-horizontal" in self.form_class.split():
|
||||||
|
bootstrap_size_match = re.findall(r"col(-(xl|lg|md|sm))?-(\d+)", self.label_class)
|
||||||
|
if bootstrap_size_match:
|
||||||
|
offset_pattern = "offset%s-%s"
|
||||||
|
items["bootstrap_checkbox_offsets"] = [
|
||||||
|
offset_pattern % (m[0], m[-1]) for m in bootstrap_size_match
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
bootstrap_size_match = re.findall(r"col-(lg|md|sm|xs)-(\d+)", self.label_class)
|
||||||
|
if bootstrap_size_match:
|
||||||
|
offset_pattern = "col-%s-offset-%s"
|
||||||
|
items["bootstrap_checkbox_offsets"] = [offset_pattern % m for m in bootstrap_size_match]
|
||||||
|
|
||||||
|
items["attrs"] = {}
|
||||||
|
if self.attrs:
|
||||||
|
items["attrs"] = self.attrs.copy()
|
||||||
|
if self.form_action:
|
||||||
|
items["attrs"]["action"] = self.form_action.strip()
|
||||||
|
if self.form_id:
|
||||||
|
items["attrs"]["id"] = self.form_id.strip()
|
||||||
|
if self.form_class:
|
||||||
|
# uni_form TEMPLATE PACK has a uniForm class by default
|
||||||
|
if template_pack == "uni_form":
|
||||||
|
items["attrs"]["class"] = "uniForm %s" % self.form_class.strip()
|
||||||
|
else:
|
||||||
|
items["attrs"]["class"] = self.form_class.strip()
|
||||||
|
else:
|
||||||
|
if template_pack == "uni_form":
|
||||||
|
items["attrs"]["class"] = self.attrs.get("class", "") + " uniForm"
|
||||||
|
if self.form_group_wrapper_class:
|
||||||
|
items["attrs"]["form_group_wrapper_class"] = self.form_group_wrapper_class
|
||||||
|
|
||||||
|
items["flat_attrs"] = flatatt(items["attrs"])
|
||||||
|
|
||||||
|
if self.inputs:
|
||||||
|
items["inputs"] = self.inputs
|
||||||
|
if self.form_error_title:
|
||||||
|
items["form_error_title"] = self.form_error_title.strip()
|
||||||
|
if self.formset_error_title:
|
||||||
|
items["formset_error_title"] = self.formset_error_title.strip()
|
||||||
|
|
||||||
|
for attribute_name, value in self.__dict__.items():
|
||||||
|
if (
|
||||||
|
attribute_name not in items
|
||||||
|
and attribute_name not in ["layout", "inputs"]
|
||||||
|
and not attribute_name.startswith("_")
|
||||||
|
):
|
||||||
|
items[attribute_name] = value
|
||||||
|
|
||||||
|
return items
|
||||||
@@ -0,0 +1,491 @@
|
|||||||
|
from django.template import Template
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
from django.utils.html import conditional_escape
|
||||||
|
|
||||||
|
from crispy_forms.utils import TEMPLATE_PACK, flatatt, get_template_pack, render_field
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNameMixin:
|
||||||
|
def get_template_name(self, template_pack):
|
||||||
|
if "%s" in self.template:
|
||||||
|
template = self.template % template_pack
|
||||||
|
else:
|
||||||
|
template = self.template
|
||||||
|
|
||||||
|
return template
|
||||||
|
|
||||||
|
|
||||||
|
class LayoutObject(TemplateNameMixin):
|
||||||
|
def __getitem__(self, slice):
|
||||||
|
return self.fields[slice]
|
||||||
|
|
||||||
|
def __setitem__(self, slice, value):
|
||||||
|
self.fields[slice] = value
|
||||||
|
|
||||||
|
def __delitem__(self, slice):
|
||||||
|
del self.fields[slice]
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.fields)
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
"""
|
||||||
|
This allows us to access self.fields list methods like append or insert, without
|
||||||
|
having to declare them one by one
|
||||||
|
"""
|
||||||
|
# Check necessary for unpickling, see #107
|
||||||
|
if "fields" in self.__dict__ and hasattr(self.fields, name):
|
||||||
|
return getattr(self.fields, name)
|
||||||
|
else:
|
||||||
|
return object.__getattribute__(self, name)
|
||||||
|
|
||||||
|
def get_field_names(self, index=None):
|
||||||
|
"""
|
||||||
|
Returns a list of lists, those lists are named pointers. First parameter
|
||||||
|
is the location of the field, second one the name of the field. Example::
|
||||||
|
|
||||||
|
[
|
||||||
|
[[0,1,2], 'field_name1'],
|
||||||
|
[[0,3], 'field_name2']
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
return self.get_layout_objects(str, index=None, greedy=True)
|
||||||
|
|
||||||
|
def get_layout_objects(self, *LayoutClasses, **kwargs):
|
||||||
|
"""
|
||||||
|
Returns a list of lists pointing to layout objects of any type matching
|
||||||
|
`LayoutClasses`::
|
||||||
|
|
||||||
|
[
|
||||||
|
[[0,1,2], 'div'],
|
||||||
|
[[0,3], 'field_name']
|
||||||
|
]
|
||||||
|
|
||||||
|
:param max_level: An integer that indicates max level depth to reach when
|
||||||
|
traversing a layout.
|
||||||
|
:param greedy: Boolean that indicates whether to be greedy. If set, max_level
|
||||||
|
is skipped.
|
||||||
|
"""
|
||||||
|
index = kwargs.pop("index", None)
|
||||||
|
max_level = kwargs.pop("max_level", 0)
|
||||||
|
greedy = kwargs.pop("greedy", False)
|
||||||
|
|
||||||
|
pointers = []
|
||||||
|
|
||||||
|
if index is not None and not isinstance(index, list):
|
||||||
|
index = [index]
|
||||||
|
elif index is None:
|
||||||
|
index = []
|
||||||
|
|
||||||
|
for i, layout_object in enumerate(self.fields):
|
||||||
|
if isinstance(layout_object, LayoutClasses):
|
||||||
|
if len(LayoutClasses) == 1 and LayoutClasses[0] == str:
|
||||||
|
pointers.append([index + [i], layout_object])
|
||||||
|
else:
|
||||||
|
pointers.append([index + [i], layout_object.__class__.__name__.lower()])
|
||||||
|
|
||||||
|
# If it's a layout object and we haven't reached the max depth limit or greedy
|
||||||
|
# we recursive call
|
||||||
|
if hasattr(layout_object, "get_field_names") and (len(index) < max_level or greedy):
|
||||||
|
new_kwargs = {"index": index + [i], "max_level": max_level, "greedy": greedy}
|
||||||
|
pointers = pointers + layout_object.get_layout_objects(*LayoutClasses, **new_kwargs)
|
||||||
|
|
||||||
|
return pointers
|
||||||
|
|
||||||
|
def get_rendered_fields(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
return "".join(
|
||||||
|
render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)
|
||||||
|
for field in self.fields
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Layout(LayoutObject):
|
||||||
|
"""
|
||||||
|
Form Layout. It is conformed by Layout objects: `Fieldset`, `Row`, `Column`, `MultiField`,
|
||||||
|
`HTML`, `ButtonHolder`, `Button`, `Hidden`, `Reset`, `Submit` and fields. Form fields
|
||||||
|
have to be strings.
|
||||||
|
Layout objects `Fieldset`, `Row`, `Column`, `MultiField` and `ButtonHolder` can hold other
|
||||||
|
Layout objects within. Though `ButtonHolder` should only hold `HTML` and BaseInput
|
||||||
|
inherited classes: `Button`, `Hidden`, `Reset` and `Submit`.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
helper.layout = Layout(
|
||||||
|
Fieldset('Company data',
|
||||||
|
'is_company'
|
||||||
|
),
|
||||||
|
Fieldset(_('Contact details'),
|
||||||
|
'email',
|
||||||
|
Row('password1', 'password2'),
|
||||||
|
'first_name',
|
||||||
|
'last_name',
|
||||||
|
HTML('<img src="/media/somepicture.jpg"/>'),
|
||||||
|
'company'
|
||||||
|
),
|
||||||
|
ButtonHolder(
|
||||||
|
Submit('Save', 'Save', css_class='button white'),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, *fields):
|
||||||
|
self.fields = list(fields)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
return self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class ButtonHolder(LayoutObject):
|
||||||
|
"""
|
||||||
|
Layout object. It wraps fields in a <div class="buttonHolder">
|
||||||
|
|
||||||
|
This is where you should put Layout objects that render to form buttons like Submit.
|
||||||
|
It should only hold `HTML` and `BaseInput` inherited objects.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
ButtonHolder(
|
||||||
|
HTML(<span style="display: hidden;">Information Saved</span>),
|
||||||
|
Submit('Save', 'Save')
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/buttonholder.html"
|
||||||
|
|
||||||
|
def __init__(self, *fields, **kwargs):
|
||||||
|
self.fields = list(fields)
|
||||||
|
self.css_class = kwargs.get("css_class", None)
|
||||||
|
self.css_id = kwargs.get("css_id", None)
|
||||||
|
self.template = kwargs.get("template", self.template)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
html = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"buttonholder": self, "fields_output": html})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class BaseInput(TemplateNameMixin):
|
||||||
|
"""
|
||||||
|
A base class to reduce the amount of code in the Input classes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/baseinput.html"
|
||||||
|
|
||||||
|
def __init__(self, name, value, **kwargs):
|
||||||
|
self.name = name
|
||||||
|
self.value = value
|
||||||
|
self.id = kwargs.pop("css_id", "")
|
||||||
|
self.attrs = {}
|
||||||
|
|
||||||
|
if "css_class" in kwargs:
|
||||||
|
self.field_classes += " %s" % kwargs.pop("css_class")
|
||||||
|
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
"""
|
||||||
|
Renders an `<input />` if container is used as a Layout object.
|
||||||
|
Input button value can be a variable in context.
|
||||||
|
"""
|
||||||
|
self.value = Template(str(self.value)).render(context)
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"input": self})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class Submit(BaseInput):
|
||||||
|
"""
|
||||||
|
Used to create a Submit button descriptor for the {% crispy %} template tag::
|
||||||
|
|
||||||
|
submit = Submit('Search the Site', 'search this site')
|
||||||
|
|
||||||
|
.. note:: The first argument is also slugified and turned into the id for the submit button.
|
||||||
|
"""
|
||||||
|
|
||||||
|
input_type = "submit"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.field_classes = "submit submitButton" if get_template_pack() == "uni_form" else "btn btn-primary"
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Button(BaseInput):
|
||||||
|
"""
|
||||||
|
Used to create a Submit input descriptor for the {% crispy %} template tag::
|
||||||
|
|
||||||
|
button = Button('Button 1', 'Press Me!')
|
||||||
|
|
||||||
|
.. note:: The first argument is also slugified and turned into the id for the button.
|
||||||
|
"""
|
||||||
|
|
||||||
|
input_type = "button"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.field_classes = "button" if get_template_pack() == "uni_form" else "btn"
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Hidden(BaseInput):
|
||||||
|
"""
|
||||||
|
Used to create a Hidden input descriptor for the {% crispy %} template tag.
|
||||||
|
"""
|
||||||
|
|
||||||
|
input_type = "hidden"
|
||||||
|
field_classes = "hidden"
|
||||||
|
|
||||||
|
|
||||||
|
class Reset(BaseInput):
|
||||||
|
"""
|
||||||
|
Used to create a Reset button input descriptor for the {% crispy %} template tag::
|
||||||
|
|
||||||
|
reset = Reset('Reset This Form', 'Revert Me!')
|
||||||
|
|
||||||
|
.. note:: The first argument is also slugified and turned into the id for the reset.
|
||||||
|
"""
|
||||||
|
|
||||||
|
input_type = "reset"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.field_classes = "reset resetButton" if get_template_pack() == "uni_form" else "btn btn-inverse"
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Fieldset(LayoutObject):
|
||||||
|
"""
|
||||||
|
Layout object. It wraps fields in a <fieldset>
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
Fieldset("Text for the legend",
|
||||||
|
'form_field_1',
|
||||||
|
'form_field_2'
|
||||||
|
)
|
||||||
|
|
||||||
|
The first parameter is the text for the fieldset legend. This text is context aware,
|
||||||
|
so you can do things like::
|
||||||
|
|
||||||
|
Fieldset("Data for {{ user.username }}",
|
||||||
|
'form_field_1',
|
||||||
|
'form_field_2'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/fieldset.html"
|
||||||
|
|
||||||
|
def __init__(self, legend, *fields, **kwargs):
|
||||||
|
self.fields = list(fields)
|
||||||
|
self.legend = legend
|
||||||
|
self.css_class = kwargs.pop("css_class", "")
|
||||||
|
self.css_id = kwargs.pop("css_id", None)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
|
||||||
|
legend = ""
|
||||||
|
if self.legend:
|
||||||
|
legend = "%s" % Template(str(self.legend)).render(context)
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
return render_to_string(
|
||||||
|
template, {"fieldset": self, "legend": legend, "fields": fields, "form_style": form_style}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MultiField(LayoutObject):
|
||||||
|
"""MultiField container. Renders to a MultiField <div>"""
|
||||||
|
|
||||||
|
template = "%s/layout/multifield.html"
|
||||||
|
field_template = "%s/multifield.html"
|
||||||
|
|
||||||
|
def __init__(self, label, *fields, **kwargs):
|
||||||
|
self.fields = list(fields)
|
||||||
|
self.label_html = label
|
||||||
|
self.label_class = kwargs.pop("label_class", "blockLabel")
|
||||||
|
self.css_class = kwargs.pop("css_class", "ctrlHolder")
|
||||||
|
self.css_id = kwargs.pop("css_id", None)
|
||||||
|
self.help_text = kwargs.pop("help_text", None)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.field_template = kwargs.pop("field_template", self.field_template)
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
# If a field within MultiField contains errors
|
||||||
|
if context["form_show_errors"]:
|
||||||
|
for field in map(lambda pointer: pointer[1], self.get_field_names()):
|
||||||
|
if field in form.errors:
|
||||||
|
self.css_class += " error"
|
||||||
|
|
||||||
|
field_template = self.field_template % template_pack
|
||||||
|
fields_output = self.get_rendered_fields(
|
||||||
|
form,
|
||||||
|
form_style,
|
||||||
|
context,
|
||||||
|
template_pack,
|
||||||
|
template=field_template,
|
||||||
|
labelclass=self.label_class,
|
||||||
|
layout_object=self,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
context.update({"multifield": self, "fields_output": fields_output})
|
||||||
|
|
||||||
|
return render_to_string(template, context.flatten())
|
||||||
|
|
||||||
|
|
||||||
|
class Div(LayoutObject):
|
||||||
|
"""
|
||||||
|
Layout object. It wraps fields in a <div>
|
||||||
|
|
||||||
|
You can set `css_id` for a DOM id and `css_class` for a DOM class. Example::
|
||||||
|
|
||||||
|
Div('form_field_1', 'form_field_2', css_id='div-example', css_class='divs')
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/div.html"
|
||||||
|
|
||||||
|
def __init__(self, *fields, **kwargs):
|
||||||
|
self.fields = list(fields)
|
||||||
|
|
||||||
|
if hasattr(self, "css_class") and "css_class" in kwargs:
|
||||||
|
self.css_class += " %s" % kwargs.pop("css_class")
|
||||||
|
if not hasattr(self, "css_class"):
|
||||||
|
self.css_class = kwargs.pop("css_class", None)
|
||||||
|
|
||||||
|
self.css_id = kwargs.pop("css_id", "")
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.flat_attrs = flatatt(kwargs)
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
return render_to_string(template, {"div": self, "fields": fields})
|
||||||
|
|
||||||
|
|
||||||
|
class Row(Div):
|
||||||
|
"""
|
||||||
|
Layout object. It wraps fields in a div whose default class is "formRow". Example::
|
||||||
|
|
||||||
|
Row('form_field_1', 'form_field_2', 'form_field_3')
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/row.html"
|
||||||
|
|
||||||
|
|
||||||
|
class Column(Div):
|
||||||
|
"""
|
||||||
|
Layout object. It wraps fields in a div so the wrapper can be used as a column. Example::
|
||||||
|
|
||||||
|
Column('form_field_1', 'form_field_2')
|
||||||
|
|
||||||
|
Depending on the template, css class associated to the div is formColumn, row, or nothing. For this last case, you
|
||||||
|
must provide css classes. Example::
|
||||||
|
|
||||||
|
Column('form_field_1', 'form_field_2', css_class='col-xs-6',)
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/layout/column.html"
|
||||||
|
|
||||||
|
|
||||||
|
class HTML:
|
||||||
|
"""
|
||||||
|
Layout object. It can contain pure HTML and it has access to the whole
|
||||||
|
context of the page where the form is being rendered.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
HTML("{% if saved %}Data saved{% endif %}")
|
||||||
|
HTML('<input type="hidden" name="{{ step_field }}" value="{{ step0 }}" />')
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, html):
|
||||||
|
self.html = html
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
|
||||||
|
return Template(str(self.html)).render(context)
|
||||||
|
|
||||||
|
|
||||||
|
class Field(LayoutObject):
|
||||||
|
"""
|
||||||
|
Layout object, It contains one field name, and you can add attributes to it easily.
|
||||||
|
For setting class attributes, you need to use `css_class`, as `class` is a Python keyword.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
Field('field_name', style="color: #333;", css_class="whatever", id="field_name")
|
||||||
|
"""
|
||||||
|
|
||||||
|
template = "%s/field.html"
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.fields = list(args)
|
||||||
|
|
||||||
|
if not hasattr(self, "attrs"):
|
||||||
|
self.attrs = {}
|
||||||
|
else:
|
||||||
|
# Make sure shared state is not edited.
|
||||||
|
self.attrs = self.attrs.copy()
|
||||||
|
|
||||||
|
if "css_class" in kwargs:
|
||||||
|
if "class" in self.attrs:
|
||||||
|
self.attrs["class"] += " %s" % kwargs.pop("css_class")
|
||||||
|
else:
|
||||||
|
self.attrs["class"] = kwargs.pop("css_class")
|
||||||
|
|
||||||
|
self.wrapper_class = kwargs.pop("wrapper_class", None)
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
|
||||||
|
# We use kwargs as HTML attributes, turning data_id='test' into data-id='test'
|
||||||
|
self.attrs.update({k.replace("_", "-"): conditional_escape(v) for k, v in kwargs.items()})
|
||||||
|
|
||||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
|
||||||
|
if extra_context is None:
|
||||||
|
extra_context = {}
|
||||||
|
if hasattr(self, "wrapper_class"):
|
||||||
|
extra_context["wrapper_class"] = self.wrapper_class
|
||||||
|
|
||||||
|
template = self.get_template_name(template_pack)
|
||||||
|
|
||||||
|
return self.get_rendered_fields(
|
||||||
|
form,
|
||||||
|
form_style,
|
||||||
|
context,
|
||||||
|
template_pack,
|
||||||
|
template=template,
|
||||||
|
attrs=self.attrs,
|
||||||
|
extra_context=extra_context,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MultiWidgetField(Field):
|
||||||
|
"""
|
||||||
|
Layout object. For fields with :class:`~django.forms.MultiWidget` as `widget`, you can pass
|
||||||
|
additional attributes to each widget.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
MultiWidgetField(
|
||||||
|
'multiwidget_field_name',
|
||||||
|
attrs=(
|
||||||
|
{'style': 'width: 30px;'},
|
||||||
|
{'class': 'second_widget_class'}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
.. note:: To override widget's css class use ``class`` not ``css_class``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.fields = list(args)
|
||||||
|
self.attrs = kwargs.pop("attrs", {})
|
||||||
|
self.template = kwargs.pop("template", self.template)
|
||||||
|
self.wrapper_class = kwargs.pop("wrapper_class", None)
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
from crispy_forms.bootstrap import Container
|
||||||
|
from crispy_forms.exceptions import DynamicError
|
||||||
|
from crispy_forms.layout import Fieldset, MultiField
|
||||||
|
|
||||||
|
|
||||||
|
class LayoutSlice:
|
||||||
|
# List of layout objects that need args passed first before fields
|
||||||
|
args_first = (Fieldset, MultiField, Container)
|
||||||
|
|
||||||
|
def __init__(self, layout, key):
|
||||||
|
self.layout = layout
|
||||||
|
if isinstance(key, int):
|
||||||
|
self.slice = slice(key, key + 1, 1)
|
||||||
|
else:
|
||||||
|
self.slice = key
|
||||||
|
|
||||||
|
def wrapped_object(self, LayoutClass, fields, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
|
||||||
|
wraps `fields` inside.
|
||||||
|
"""
|
||||||
|
if args:
|
||||||
|
if isinstance(fields, list):
|
||||||
|
fields = tuple(fields)
|
||||||
|
else:
|
||||||
|
fields = (fields,)
|
||||||
|
|
||||||
|
if LayoutClass in self.args_first:
|
||||||
|
arguments = args + fields
|
||||||
|
else:
|
||||||
|
arguments = fields + args
|
||||||
|
|
||||||
|
return LayoutClass(*arguments, **kwargs)
|
||||||
|
else:
|
||||||
|
if isinstance(fields, list):
|
||||||
|
return LayoutClass(*fields, **kwargs)
|
||||||
|
else:
|
||||||
|
return LayoutClass(fields, **kwargs)
|
||||||
|
|
||||||
|
def pre_map(self, function):
|
||||||
|
"""
|
||||||
|
Iterates over layout objects pointed in `self.slice` executing `function` on them.
|
||||||
|
It passes `function` penultimate layout object and the position where to find last one
|
||||||
|
"""
|
||||||
|
if isinstance(self.slice, slice):
|
||||||
|
for i in range(*self.slice.indices(len(self.layout.fields))):
|
||||||
|
function(self.layout, i)
|
||||||
|
|
||||||
|
elif isinstance(self.slice, list):
|
||||||
|
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
|
||||||
|
for pointer in self.slice:
|
||||||
|
position = pointer[0]
|
||||||
|
|
||||||
|
# If it's pointing first level
|
||||||
|
if len(position) == 1:
|
||||||
|
function(self.layout, position[-1])
|
||||||
|
else:
|
||||||
|
layout_object = self.layout.fields[position[0]]
|
||||||
|
for i in position[1:-1]:
|
||||||
|
layout_object = layout_object.fields[i]
|
||||||
|
|
||||||
|
try:
|
||||||
|
function(layout_object, position[-1])
|
||||||
|
except IndexError:
|
||||||
|
# We could avoid this exception, recalculating pointers.
|
||||||
|
# However this case is most of the time an undesired behavior
|
||||||
|
raise DynamicError(
|
||||||
|
"Trying to wrap a field within an already wrapped field, \
|
||||||
|
recheck your filter or layout"
|
||||||
|
)
|
||||||
|
|
||||||
|
def wrap(self, LayoutClass, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
|
||||||
|
`args` and `kwargs` passed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def wrap_object(layout_object, j):
|
||||||
|
layout_object.fields[j] = self.wrapped_object(LayoutClass, layout_object.fields[j], *args, **kwargs)
|
||||||
|
|
||||||
|
self.pre_map(wrap_object)
|
||||||
|
|
||||||
|
def wrap_once(self, LayoutClass, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
|
||||||
|
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
|
||||||
|
`LayoutClass`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def wrap_object_once(layout_object, j):
|
||||||
|
if not isinstance(layout_object, LayoutClass):
|
||||||
|
layout_object.fields[j] = self.wrapped_object(LayoutClass, layout_object.fields[j], *args, **kwargs)
|
||||||
|
|
||||||
|
self.pre_map(wrap_object_once)
|
||||||
|
|
||||||
|
def wrap_together(self, LayoutClass, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
|
||||||
|
instance with `args` and `kwargs` passed.
|
||||||
|
"""
|
||||||
|
if isinstance(self.slice, slice):
|
||||||
|
# The start of the slice is replaced
|
||||||
|
start = self.slice.start if self.slice.start is not None else 0
|
||||||
|
self.layout.fields[start] = self.wrapped_object(
|
||||||
|
LayoutClass, self.layout.fields[self.slice], *args, **kwargs
|
||||||
|
)
|
||||||
|
|
||||||
|
# The rest of places of the slice are removed, as they are included in the previous
|
||||||
|
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))):
|
||||||
|
if i != start:
|
||||||
|
del self.layout.fields[i]
|
||||||
|
|
||||||
|
elif isinstance(self.slice, list):
|
||||||
|
raise DynamicError("wrap_together doesn't work with filter, only with [] operator")
|
||||||
|
|
||||||
|
def map(self, function):
|
||||||
|
"""
|
||||||
|
Iterates over layout objects pointed in `self.slice` executing `function` on them
|
||||||
|
It passes `function` last layout object
|
||||||
|
"""
|
||||||
|
if isinstance(self.slice, slice):
|
||||||
|
for i in range(*self.slice.indices(len(self.layout.fields))):
|
||||||
|
function(self.layout.fields[i])
|
||||||
|
|
||||||
|
elif isinstance(self.slice, list):
|
||||||
|
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
|
||||||
|
for pointer in self.slice:
|
||||||
|
position = pointer[0]
|
||||||
|
|
||||||
|
layout_object = self.layout.fields[position[0]]
|
||||||
|
for i in position[1:]:
|
||||||
|
previous_layout_object = layout_object
|
||||||
|
layout_object = layout_object.fields[i]
|
||||||
|
|
||||||
|
# If update_attrs is applied to a string, we call to its wrapping layout object
|
||||||
|
if function.__name__ == "update_attrs" and isinstance(layout_object, str):
|
||||||
|
function(previous_layout_object)
|
||||||
|
else:
|
||||||
|
function(layout_object)
|
||||||
|
|
||||||
|
def update_attributes(self, **original_kwargs):
|
||||||
|
"""
|
||||||
|
Updates attributes of every layout object pointed in `self.slice` using kwargs
|
||||||
|
"""
|
||||||
|
|
||||||
|
def update_attrs(layout_object):
|
||||||
|
kwargs = original_kwargs.copy()
|
||||||
|
if hasattr(layout_object, "attrs"):
|
||||||
|
if "css_class" in kwargs:
|
||||||
|
if "class" in layout_object.attrs:
|
||||||
|
layout_object.attrs["class"] += " %s" % kwargs.pop("css_class")
|
||||||
|
else:
|
||||||
|
layout_object.attrs["class"] = kwargs.pop("css_class")
|
||||||
|
layout_object.attrs.update(kwargs)
|
||||||
|
|
||||||
|
self.map(update_attrs)
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
<div class="accordion-group">
|
||||||
|
<div class="accordion-heading">
|
||||||
|
<a class="accordion-toggle" data-toggle="collapse" data-parent="#{{ div.data_parent }}" href="#{{ div.css_id }}">{{ div.name }}</a>
|
||||||
|
</div>
|
||||||
|
<div id="{{ div.css_id }}" class="accordion-body collapse{% if div.active %} in{% endif %}" >
|
||||||
|
<div class="accordion-inner">
|
||||||
|
{{ fields|safe }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
<div class="accordion" id="{{ accordion.css_id }}">
|
||||||
|
{{ content|safe }}
|
||||||
|
</div>
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
{% for fieldset in form.fieldsets %}
|
||||||
|
<fieldset class="fieldset-{{ forloop.counter }} {{ fieldset.classes }}">
|
||||||
|
{% if fieldset.legend %}
|
||||||
|
<legend>{{ fieldset.legend }}</legend>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if fieldset.description %}
|
||||||
|
<p class="description">{{ fieldset.description }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% for field in fieldset %}
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
{% include "bootstrap/field.html" %}
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% if not forloop.last or not fieldset_open %}
|
||||||
|
</fieldset>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{% if form.form_html %}
|
||||||
|
{% if include_media %}{{ form.media }}{% endif %}
|
||||||
|
{% if form_show_errors %}
|
||||||
|
{% include "bootstrap/errors.html" %}
|
||||||
|
{% endif %}
|
||||||
|
{{ form.form_html }}
|
||||||
|
{% else %}
|
||||||
|
{% include "bootstrap/uni_form.html" %}
|
||||||
|
{% endif %}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
{% if form.non_field_errors %}
|
||||||
|
<div class="alert alert-block alert-error">
|
||||||
|
{% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %}
|
||||||
|
<ul>
|
||||||
|
{{ form.non_field_errors|unordered_list }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{% if formset.non_form_errors %}
|
||||||
|
<div class="alert alert-block alert-error">
|
||||||
|
{% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %}
|
||||||
|
<ul>
|
||||||
|
{{ formset.non_form_errors|unordered_list }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
<{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" class="control-group{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
{% if field.label and not field|is_checkbox and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field|is_checkboxselectmultiple %}
|
||||||
|
{% include 'bootstrap/layout/checkboxselectmultiple.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field|is_radioselect %}
|
||||||
|
{% include 'bootstrap/layout/radioselect.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
|
||||||
|
<div class="controls">
|
||||||
|
{% if field|is_checkbox and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="checkbox {% if field.field.required %}requiredField{% endif %}">
|
||||||
|
{% crispy_field field %}
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %}
|
||||||
|
{% else %}
|
||||||
|
{% crispy_field field %}
|
||||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</{% if tag %}{{ tag }}{% else %}div{% endif %}>
|
||||||
|
{% endif %}
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
<div{% if alert.css_id %} id="{{ alert.css_id }}"{% endif %}{% if alert.css_class %} class="{{ alert.css_class }}"{% endif %}>
|
||||||
|
{% if dismiss %}<button type="button" class="close" data-dismiss="alert">×</button>{% endif %}
|
||||||
|
{{ content|safe }}
|
||||||
|
</div>
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<input type="{{ input.input_type }}"
|
||||||
|
name="{% if input.name|wordcount > 1 %}{{ input.name|slugify }}{% else %}{{ input.name }}{% endif %}"
|
||||||
|
value="{{ input.value }}"
|
||||||
|
{% if input.input_type != "hidden" %}
|
||||||
|
class="{{ input.field_classes }}"
|
||||||
|
id="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}"
|
||||||
|
{% endif %}
|
||||||
|
{{ input.flat_attrs|safe }}
|
||||||
|
/>
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<button {{ button.flat_attrs|safe }}>{{ button.content|safe }}</button>
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
<div {% if buttonholder.css_id %}id="{{ buttonholder.css_id }}"{% endif %}
|
||||||
|
class="buttonHolder{% if buttonholder.css_class %} {{ buttonholder.css_class }}{% endif %}">
|
||||||
|
{{ fields_output|safe }}
|
||||||
|
</div>
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{% load crispy_forms_filters %}
|
||||||
|
{% load l10n %}
|
||||||
|
|
||||||
|
<div class="controls"{% if flat_attrs %} {{ flat_attrs|safe }}{% endif %}>
|
||||||
|
{% include 'bootstrap/layout/field_errors_block.html' %}
|
||||||
|
|
||||||
|
{% for choice in field.field.choices %}
|
||||||
|
<label class="checkbox{% if inline_class %} {{ inline_class }}{% endif %}" for="id_{{ field.html_name }}_{{ forloop.counter0 }}">
|
||||||
|
<input type="checkbox"{% if choice.0 in field.value or choice.0|stringformat:"s" in field.value or choice.0|stringformat:"s" == field.value|default_if_none:""|stringformat:"s" %} checked{% endif %} name="{{ field.html_name }}" id="id_{{ field.html_name }}_{{ forloop.counter0 }}" value="{{ choice.0|unlocalize }}" {% if field.field.disabled %}disabled="true"{% endif %} {{ field.field.widget.attrs|flatatt }}>{{ choice.1|unlocalize }}
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{% include 'bootstrap/layout/help_text.html' %}
|
||||||
|
</div>
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
|
||||||
|
{% if field.label %}
|
||||||
|
<label for="{{ field.auto_id }}" class="control-label{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% include 'bootstrap/layout/checkboxselectmultiple.html' %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %} class="{{ div.css_class|default:'' }}" {{ div.flat_attrs|safe }}>
|
||||||
|
{{ fields|safe }}
|
||||||
|
</div>
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %}
|
||||||
|
{% if div.css_class %}class="{{ div.css_class }}"{% endif %} {{ div.flat_attrs|safe }}>
|
||||||
|
{{ fields|safe }}
|
||||||
|
</div>
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
{% if form_show_errors and field.errors %}
|
||||||
|
{% for error in field.errors %}
|
||||||
|
<span id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="help-inline"><strong>{{ error }}</strong></span>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
{% if form_show_errors and field.errors %}
|
||||||
|
{% for error in field.errors %}
|
||||||
|
<p id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="help-block"><strong>{{ error }}</strong></p>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}" {{ div.flat_attrs|safe }}>
|
||||||
|
{% if field.label and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="control-label{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="controls">
|
||||||
|
<div class="input-append">
|
||||||
|
{% crispy_field field %}
|
||||||
|
{{ buttons|safe }}
|
||||||
|
</div>
|
||||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<fieldset {% if fieldset.css_id %}id="{{ fieldset.css_id }}"{% endif %}
|
||||||
|
{% if fieldset.css_class or form_style %}class="{{ fieldset.css_class }} {{ form_style }}"{% endif %}
|
||||||
|
{{ fieldset.flat_attrs|safe }}>
|
||||||
|
{% if legend %}<legend>{{ legend|safe }}</legend>{% endif %}
|
||||||
|
{{ fields|safe }}
|
||||||
|
</fieldset>
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
<div{% if formactions.attrs %} {{ formactions.flat_attrs|safe }}{% endif %} class="form-actions">
|
||||||
|
{{ fields_output|safe }}
|
||||||
|
</div>
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{% if field.help_text %}
|
||||||
|
{% if help_text_inline %}
|
||||||
|
<span id="hint_{{ field.auto_id }}" class="help-inline">{{ field.help_text|safe }}</span>
|
||||||
|
{% else %}
|
||||||
|
<p id="hint_{{ field.auto_id }}" class="help-block">{{ field.help_text|safe }}</p>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
{% if help_text_inline and not error_text_inline %}
|
||||||
|
{% include 'bootstrap/layout/help_text.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if error_text_inline %}
|
||||||
|
{% include 'bootstrap/layout/field_errors.html' %}
|
||||||
|
{% else %}
|
||||||
|
{% include 'bootstrap/layout/field_errors_block.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if not help_text_inline %}
|
||||||
|
{% include 'bootstrap/layout/help_text.html' %}
|
||||||
|
{% endif %}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
|
||||||
|
{% if field.label %}
|
||||||
|
<label for="{{ field.id_for_label }}"{% if labelclass %} class="{{ labelclass }}"{% endif %}>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field|is_checkbox %}
|
||||||
|
{% crispy_field field %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field.label %}
|
||||||
|
{{ field.label }}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if not field|is_checkbox %}
|
||||||
|
{% crispy_field field %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field.label %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% endif %}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
|
||||||
|
{% if field.label and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="control-label{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="controls">
|
||||||
|
<div class="{% if crispy_prepended_text %}input-prepend{% endif %} {% if crispy_appended_text %}input-append{% endif %}">
|
||||||
|
{% if crispy_prepended_text %}<span class="{% if not field|is_select %}add-on{% endif %}{% if active %} active{% endif %}">{{ crispy_prepended_text|safe }}</span>{% endif %}
|
||||||
|
{% crispy_field field %}
|
||||||
|
{% if crispy_appended_text %}<span class="{% if not field|is_select %}add-on{% endif %}{% if active %} active{% endif %}">{{ crispy_appended_text|safe }}</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{% load crispy_forms_filters %}
|
||||||
|
{% load l10n %}
|
||||||
|
|
||||||
|
<div class="controls"{% if flat_attrs %} {{ flat_attrs|safe }}{% endif %}>
|
||||||
|
{% include 'bootstrap/layout/field_errors_block.html' %}
|
||||||
|
|
||||||
|
{% for choice in field.field.choices %}
|
||||||
|
<label for="id_{{ field.html_name }}_{{ forloop.counter0 }}" class="radio{% if inline_class %} {{ inline_class }}{% endif %}">
|
||||||
|
<input type="radio"{% if choice.0|stringformat:"s" == field.value|default_if_none:""|stringformat:"s" %} checked{% endif %} name="{{ field.html_name }}" id="id_{{ field.html_name }}_{{ forloop.counter0 }}" value="{{ choice.0|unlocalize }}" {% if field.field.disabled %}disabled="true"{% endif %} {{ field.field.widget.attrs|flatatt }}>{{ choice.1|unlocalize }}
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{% include 'bootstrap/layout/help_text.html' %}
|
||||||
|
</div>
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
|
||||||
|
{% if field.label %}
|
||||||
|
<label for="{{ field.auto_id }}" class="control-label{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% include 'bootstrap/layout/radioselect.html' %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %} class="row {{ div.css_class|default:'' }}" {{ div.flat_attrs|safe }}>
|
||||||
|
{{ fields|safe }}
|
||||||
|
</div>
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<li class="tab-pane{% if 'active' in link.css_class %} active{% endif %}"><a href="#{{ link.css_id }}" data-toggle="tab">{{ link.name|capfirst }}{% if tab.errors %}!{% endif %}</a></li>
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<ul{% if tabs.css_id %} id="{{ tabs.css_id }}"{% endif %} class="nav nav-tabs">
|
||||||
|
{{ links|safe }}
|
||||||
|
</ul>
|
||||||
|
<div class="tab-content">
|
||||||
|
{{ content|safe }}
|
||||||
|
</div>
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
<div class="control-label{% if field.field.required %} requiredField{% endif %}">{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}</div>
|
||||||
|
<div class="controls">
|
||||||
|
<span {{ flat_attrs|safe }}>{% if field.value %}{{ field.value }}{% endif %}</span>
|
||||||
|
{% include 'bootstrap/layout/help_text.html' %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
{% load crispy_forms_tags %}
|
||||||
|
{% load crispy_forms_utils %}
|
||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
{% specialspaceless %}
|
||||||
|
{% if formset_tag %}
|
||||||
|
<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}>
|
||||||
|
{% endif %}
|
||||||
|
{% if formset_method|lower == 'post' and not disable_csrf %}
|
||||||
|
{% csrf_token %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{{ formset.management_form|crispy }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table{% if form_id %} id="{{ form_id }}_table"{% endif%} class="table table-striped table-condensed">
|
||||||
|
<thead>
|
||||||
|
{% if formset.readonly and not formset.queryset.exists %}
|
||||||
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
{% for field in formset.forms.0 %}
|
||||||
|
{% if field.label and not field.is_hidden %}
|
||||||
|
<th for="{{ field.auto_id }}" class="control-label {% if field.field.required and not field|is_checkbox %}requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required and not field|is_checkbox %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</th>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% endif %}
|
||||||
|
</thead>
|
||||||
|
|
||||||
|
<tbody>
|
||||||
|
<tr class="hidden empty-form">
|
||||||
|
{% for field in formset.empty_form %}
|
||||||
|
{% include 'bootstrap/field.html' with tag="td" form_show_labels=False %}
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
{% for form in formset %}
|
||||||
|
{% if form_show_errors and not form.is_extra %}
|
||||||
|
{% include "bootstrap/errors.html" %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<tr>
|
||||||
|
{% for field in form %}
|
||||||
|
{% include 'bootstrap/field.html' with tag="td" form_show_labels=False %}
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
{% if inputs %}
|
||||||
|
<div class="form-actions">
|
||||||
|
{% for input in inputs %}
|
||||||
|
{% include "bootstrap/layout/baseinput.html" %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if formset_tag %}</form>{% endif %}
|
||||||
|
{% endspecialspaceless %}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
{% load crispy_forms_utils %}
|
||||||
|
|
||||||
|
{% specialspaceless %}
|
||||||
|
{% if include_media %}{{ form.media }}{% endif %}
|
||||||
|
{% if form_show_errors %}
|
||||||
|
{% include "bootstrap/errors.html" %}
|
||||||
|
{% endif %}
|
||||||
|
{% for field in form %}
|
||||||
|
{% include field_template %}
|
||||||
|
{% endfor %}
|
||||||
|
{% endspecialspaceless %}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
{% with formset.management_form as form %}
|
||||||
|
{% include 'bootstrap/uni_form.html' %}
|
||||||
|
{% endwith %}
|
||||||
|
{% for form in formset %}
|
||||||
|
<div class="multiField">
|
||||||
|
{% include 'bootstrap/uni_form.html' %}
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
{% load crispy_forms_utils %}
|
||||||
|
|
||||||
|
{% specialspaceless %}
|
||||||
|
{% if form_tag %}<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if form.is_multipart %} enctype="multipart/form-data"{% endif %}>{% endif %}
|
||||||
|
{% if form_method|lower == 'post' and not disable_csrf %}
|
||||||
|
{% csrf_token %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% include "bootstrap/display_form.html" %}
|
||||||
|
|
||||||
|
{% if inputs %}
|
||||||
|
<div class="form-actions">
|
||||||
|
{% for input in inputs %}
|
||||||
|
{% include "bootstrap/layout/baseinput.html" %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if form_tag %}</form>{% endif %}
|
||||||
|
{% endspecialspaceless %}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
{% load crispy_forms_tags %}
|
||||||
|
{% load crispy_forms_utils %}
|
||||||
|
|
||||||
|
{% specialspaceless %}
|
||||||
|
{% if formset_tag %}
|
||||||
|
<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}>
|
||||||
|
{% endif %}
|
||||||
|
{% if formset_method|lower == 'post' and not disable_csrf %}
|
||||||
|
{% csrf_token %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{{ formset.management_form|crispy }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% include "bootstrap/errors_formset.html" %}
|
||||||
|
|
||||||
|
{% for form in formset %}
|
||||||
|
{% include "bootstrap/display_form.html" %}
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{% if inputs %}
|
||||||
|
<div class="form-actions">
|
||||||
|
{% for input in inputs %}
|
||||||
|
{% include "bootstrap/layout/baseinput.html" %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if formset_tag %}</form>{% endif %}
|
||||||
|
{% endspecialspaceless %}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
<div class="panel panel-default">
|
||||||
|
<div class="panel-heading">
|
||||||
|
<h4 class="panel-title">
|
||||||
|
<a class="accordion-toggle" data-toggle="collapse" data-parent="#{{ div.data_parent }}" href="#{{ div.css_id }}">{{ div.name }}</a>
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
<div id="{{ div.css_id }}" class="panel-collapse collapse{% if div.active %} in{% endif %}" >
|
||||||
|
<div class="panel-body">
|
||||||
|
{{ fields|safe }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
<div class="panel-group" id="{{ accordion.css_id }}">
|
||||||
|
{{ content|safe }}
|
||||||
|
</div>
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
{% for fieldset in form.fieldsets %}
|
||||||
|
<fieldset class="fieldset-{{ forloop.counter }} {{ fieldset.classes }}">
|
||||||
|
{% if fieldset.legend %}
|
||||||
|
<legend>{{ fieldset.legend }}</legend>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if fieldset.description %}
|
||||||
|
<p class="description">{{ fieldset.description }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% for field in fieldset %}
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
{% include "bootstrap3/field.html" %}
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% if not forloop.last or not fieldset_open %}
|
||||||
|
</fieldset>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{% if form.form_html %}
|
||||||
|
{% if include_media %}{{ form.media }}{% endif %}
|
||||||
|
{% if form_show_errors %}
|
||||||
|
{% include "bootstrap3/errors.html" %}
|
||||||
|
{% endif %}
|
||||||
|
{{ form.form_html }}
|
||||||
|
{% else %}
|
||||||
|
{% include "bootstrap3/uni_form.html" %}
|
||||||
|
{% endif %}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
{% if form.non_field_errors %}
|
||||||
|
<div class="alert alert-block alert-danger">
|
||||||
|
{% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %}
|
||||||
|
<ul>
|
||||||
|
{{ form.non_field_errors|unordered_list }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{% if formset.non_form_errors %}
|
||||||
|
<div class="alert alert-block alert-danger">
|
||||||
|
{% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %}
|
||||||
|
<ul>
|
||||||
|
{{ formset.non_form_errors|unordered_list }}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
{% load crispy_forms_field %}
|
||||||
|
|
||||||
|
{% if field.is_hidden %}
|
||||||
|
{{ field }}
|
||||||
|
{% else %}
|
||||||
|
{% if field|is_checkbox %}
|
||||||
|
<div class="form-group">
|
||||||
|
{% if label_class %}
|
||||||
|
<div class="controls {% for offset in bootstrap_checkbox_offsets %}{{ offset }} {% endfor %}{{ field_class }}">
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
<{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" {% if not field|is_checkbox %}class="form-group{% else %}class="checkbox{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
|
||||||
|
{% if field.label and not field|is_checkbox and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="control-label {{ label_class }}{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field|is_checkboxselectmultiple %}
|
||||||
|
{% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if field|is_radioselect %}
|
||||||
|
{% include 'bootstrap3/layout/radioselect.html' %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
|
||||||
|
{% if field|is_checkbox and form_show_labels %}
|
||||||
|
<label for="{{ field.id_for_label }}" class="{% if field.field.required %} requiredField{% endif %}">
|
||||||
|
{% crispy_field field %}
|
||||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
{% include 'bootstrap3/layout/help_text_and_errors.html' %}
|
||||||
|
{% else %}
|
||||||
|
<div class="controls {{ field_class }}">
|
||||||
|
{% if field|is_multivalue %}
|
||||||
|
{% crispy_field field %}
|
||||||
|
{% else %}
|
||||||
|
{% crispy_field field 'class' 'form-control' %}
|
||||||
|
{% endif %}
|
||||||
|
{% include 'bootstrap3/layout/help_text_and_errors.html' %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</{% if tag %}{{ tag }}{% else %}div{% endif %}>
|
||||||
|
{% if field|is_checkbox %}
|
||||||
|
{% if label_class %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
{% if inputs %}
|
||||||
|
<div class="form-group">
|
||||||
|
{% if label_class %}
|
||||||
|
<div class="aab controls {{ label_class }}"></div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="controls {{ field_class }}">
|
||||||
|
{% for input in inputs %}
|
||||||
|
{% include "bootstrap3/layout/baseinput.html" %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
<div{% if alert.css_id %} id="{{ alert.css_id }}"{% endif %}{% if alert.css_class %} class="{{ alert.css_class }}"{% endif %}>
|
||||||
|
{% if dismiss %}<button type="button" class="close" data-dismiss="alert">×</button>{% endif %}
|
||||||
|
{{ content|safe }}
|
||||||
|
</div>
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<input type="{{ input.input_type }}"
|
||||||
|
name="{% if input.name|wordcount > 1 %}{{ input.name|slugify }}{% else %}{{ input.name }}{% endif %}"
|
||||||
|
value="{{ input.value }}"
|
||||||
|
{% if input.input_type != "hidden" %}
|
||||||
|
class="{{ input.field_classes }}"
|
||||||
|
id="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}"
|
||||||
|
{% endif %}
|
||||||
|
{{ input.flat_attrs|safe }}
|
||||||
|
/>
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<button {{ button.flat_attrs|safe }}>{{ button.content|safe }}</button>
|
||||||
Loaded 100 of 4698 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user