django-crucrudile¶
Installation¶
At this time, the only requirements to run django-crucrudile are Python (2.7, 3.2, 3.3), and Django (1.6).
Note : support for Python 2.6 can be added pretty easily, ping me if you need it.
As django-crucrudile is still in the initial development phase, I did not yet upload it to the Python package index. To install it, you can either install it as a Python egg with pip, or download the source and run setup.py install.
To install with pip:
pip install -e git+https://github.com/pstch/django-crucrudile.git@master#egg=django-crucrudile
(This installs the latest release (major, minor or patch), use @develop to install development version. You can also use @tag, replacing tag by a release name (ex: ‘v1.4.1’) (Git tag, see Releases tab in GitHub).
To install from source
git clone https://github.com/pstch/django-crucrudile.git
cd django-crucrudile
python setup.py install
If you want the development version (default branch is master, containing latest release), run git checkout develop before python setup.py install
django-crucrudile is a Python package, and it does not need to be included as an application (in INSTALLED_APPS) in Django. You only need to import the needed modules in your Python files.
Getting started¶
Getting django-crucrudile to automatically generate your URL patterns is a 4-step process :
1. Views¶
django-crucrudile needs some functions and attributes defined on the view class, in order to get informations about what kind of action the view is representing, and what arguments are needed. All these functions and attributes are defined in django_crucrudile.views.mixins.ModelActionMixin.
It is perfectly possible to use a Django generic view (or any view), that does not define the functions and attributes aforementionned, there are two ways to do so:
- Subclass a view, and make it inherit from ModelActionMixin
- Don’t do anything, and make_model_mixin will patch the given view argument with the functions and attributes of ModelActionMixin (this behaviour can be disabled using the no_auto_view_mixin argument to make_model_mixin
Either way, in case the view needs URL arguments, you will have to define in the url_args attribute of your view. This attribute should be a list of needed arguments (express the arguments as regex capture groups, same as in urls.py). Example for a numeric argument:
DetailView.url_args = ['(?P<pk>\d+)',]
Note : the url_args value can also be a list of lists, in that case django-crucrudile will create different URL arguments for the different URL arguments combinations. This can be useful to have a model view that can be accessed both by slug, and both by numeric id.
Usually, the “action name” is taken from the view class name, stripped of the tailing “View”, and converted from CamelCase to dash-separated text. For example, a FilteredListView will have, as action name, filtered-list. You can override this behaviour by defining the action attribute on your view.
Personally, I define my views in a views.py, using Django’s generic views as a base, making it inherit from ModelActionMixin, and setting the url_args and action attributes. But you can also just set the url_args attribute on the detail, update and delete Django generic views (these views require an URL argument to know which object it needs to handle), and use these views in make_model_mixin.
2. Model mixins¶
Once you defined your views (or the needed arguments on generic views) defining your model mixins is very straightforward, just use make_model_mixin, with a view as argument, or make_model_mixins with a list of views as argument:
Listable = make_model_mixin(ListView)
Detailable = make_model_mixin(DetailView)
Or:
Listable, Detailable = make_model_mixin([ListView, DetailView])
You now have Listable and Detailable defined, and they are “model mixins” that can be used a base classes in your Model.
make_model_mixin can also take other arguments, to define view-specific functions on your Model, or to set model-specific arguments to use when calling the view. Please see the django_crucrudile.models.mixins.make_model_mixin() documentation for more information.
3. Models¶
Example:
class Book(Listable, Detailable, models.Model):
name = models.CharField(max_length=32)
author = models.ForeignKey(Author)
...
Your Book now inherits functions from AutoPatternsMixin (the base class for model mixins), that you can use to get the model’s URL patterns. See the django_crucrudile.models.mixins.AutoPatternsMixin documentation for more information.
4. urls.py¶
To get the list of url objects for a specific Model (here Book), you can use Book.get_url_patterns(), and use the return value of this function in your urls.py:
urlpatterns = [
Book.get_url_patterns(),
]
Or you could loop through your models, and append the URL patterns to urlpatterns:
from itertools import chain
from models import Book, Author
model_list = Book, Author
urlpatterns = [model.get_url_patterns() for model in model_list]
Yes, your urls.py now contains four lines !
Reference¶
django_crucrudile.models.mixins module¶
Model mixin function and base class¶
This module contains a base model mixin that defines functions related to URL pattern generation, and URL handling, and a function that can create real model mixins (based on the aforementionned base model mixin) for a given view class.
This module is the main part of django-crucrudile.
- django_crucrudile.models.mixins.make_model_mixin(view_class, extra_args=None, extra_funcs=None, no_auto_view_mixin=False)¶
Return a generated Model mixin for a given view HAHA.
Parameters: - view (django.views.generic.View) – View to use for this mixin (this view should subclass ModelActionMixin)
- extra_args (dict) – Dictionary of keyword arguments for the view (the dict value is the argument value, and might be a callable, and will be called with the model as argument)
- extra_funcs (dict) – Dictionary of functions to add on the model mixin. (the dict key is the function name, and might be a callable, and will be called with view as argument)
- no_auto_view_mixin (bool) – Disable autopatching of view with ModelActionMixin. (When view_class is missing a method or attribute from ModelActionMixin, it is automatically added (and bound if needed). Set this to True to disable this behaviour.)
Returns: Model mixin for view_class
Return type: subclass of AutoPatternsMixin
- django_crucrudile.models.mixins.make_model_mixins(views, no_auto_view_mixin=False)¶
Return a list of model action mixins for the given list of views.
Parameters: - views (list) – Views to make mixins for. Should contain tuples (with at least one item and at most three), themselves containing : view_class, extra_args (optional), extra_func (optional). For a definition of the above keywords, please see the documentation of make_model_mixin.
- no_auto_view_mixin – Disable autopatching of view with ModelActionMixin (when view_class is missing a method or attribute from ModelActionMixin, it is automatically added (and bound if needed) to view_class. Set this to True to disable this behaviour. See docs fr more information)
Returns: Model action mixins for views
Return type: list
- class django_crucrudile.models.mixins.AutoPatternsMixin¶
Bases: object
Base mixin for all action model mixins
- url_namespaces = None¶
Attribute url_namespaces: List of URL namespaces
- classmethod get_model_name()¶
Get the model name (example for FooBarTestModel : ‘foobartestmodel’)
Returns: Model name Return type: str
- classmethod get_views()¶
Return list of views for this model
This class method is overriden by model mixin classes, so that the resulting Model object (which subclasses model mixins classes) can get the list of the views used for this Model with get_views().
When overriden in a model mixin class, get_views() should always get the current list of views using super(...).get_views) before appending a new view.
Returns: Views for this model Return type: list
- classmethod get_args_by_view(view)¶
Return dict of keyword arguments for a view
This class method is overriden by model mixin classes, so that the resulting Model object (which subclasses model mixin classes) can get the dictionary of view arguments for each view used in this Model, with get_args_by_view(view).
When overriden in a ModelMixin class or by the user, get_args_by_view should always get the current list of views using super(...).get_views) before appending a new View. Usually, args are tretrieved using super, then if the ‘view’ kwarg is the view on which we want to set arguments, we update the args dictionary with another dictionary.
Parameters: view (view class) – View to get the args for Returns: Arguments for view given in view, or empty dict Return type: dict Raises ImproperlyConfigured: view not in cls.get_views()
- classmethod get_url_namespaces(no_content_types=False)¶
Returns the list of URL namespaces to use when creating the URLs.
To disable usage of URL namespaces, set this to return an empty list. You will need to override this if don’t want the application name as a namespace.
Parameters: no_content_types – Disable usage of content types framework (fallback to Django internals (model._meta...)) Type: no_content_types: bool Returns: URL namespaces Return type: list
- classmethod get_url_name(view, prefix=False)¶
Return the URL name for a given view
Compiles the URL name using view.get_action_name and cls.get_model_name.
get_model_name can be None, in which case the URL name will be compiled using the action
Parameters: - view (view class) – View class to get the URL name for
- prefix (bool) – Add namespaces prefix to URL name (by default, No)
Returns: URL name
Return type: str
- classmethod get_url_prefix()¶
Return path prefix
By default, returns an empty string (so that the URL is prefixed directly in urls.py), but it’s possible to return a prefix based on get_url_namespaces() too.
Returns: URL prefix Return type: str
- classmethod get_url_patterns_by_view(view)¶
Get list of URL patterns for a given view and its URL parts (combinations of URL arguments specification)
param view: View to get patterns for type view: view class return: URL patterns of this Model for a given view rtype: list raise ImproperlyConfigured: If view not in get_views()
- classmethod get_url_patterns(views=None)¶
Get list of URL patterns for all views
Parameters: views (list) – Get URL patterns for these views only. Each view must be present in the list returned by get_views() Returns: All URL patterns of this Model (for all views, or for views in views argument) Return type: list
django_crucrudile.views.mixins module¶
View mixin¶
This module contains a base view mixin to specify an interface, that will be used by model mixins (in models.mixins) to get metadata about the view :
- Action name from ModelActionMixin.get_action_name()
- Will be used for URLs, URL names and get_*_url functions. when used in URLs or get_*_url functions, it will be underscore-separated, otherwise dash-separated.
- URL parts from ModelActionMixin.get_url_parts()
- Will be used for URLs. compiles the multiple possible combinations of URL arguments to create a list of possible URL specifications for this view (which will be joined to the model name by the model mixin).
- class django_crucrudile.views.mixins.ModelActionMixin¶
Bases: object
This Mixin may be used by any view to set parameters used by model mixins for the URL computation, such as the action name (e.g., list, filtered-list, detail, create, etc...) and URL arguments (ex: (?P<pk>\d+)), if needed.
- action = None¶
Attribute action: Action name, should be dash-separated. (See examples in class documentation)
- url_args = None¶
Attribute url_args: List of arguments (capturing groups, as used in Django’s URL regular expressions). (See examples in class documentation)
- classmethod get_fallback_action_name()¶
Guess a fallback action name, based on the view class name, stripped of the tailing View, and converted from CamelCase (capitalized words) to words_separated_by_underscore.
Returns: Fallback action name Return type: str
- classmethod get_action_name()¶
Return the action name, using the action attribute of the view, or, if not specified, get_fallback_action_name().
Action name will be cached in cls.action (only computed on first call)
Returns: Action name Return type: str
- classmethod get_underscored_action_name()¶
Return the underscored action name, which is the same as the action name except all dashes are replaced by underscores.
Used in action-specific function names, and in URL paths.
Returns: Underscored action name Return type: str
- classmethod get_url_args()¶
Return the list of regex specifications for URL arguments, as in urls.py. Will be joined with a forward slash (‘/’). Can be a list of lists, in which case multiple URL patterns will be defined (with the same name).
Returns: URL argument specification Return type: list
- classmethod get_url_part(args)¶
Return the URL part for given list of arguments
Parameters: args (list) – URL argument specification to compile URL part for Returns: Compiled URL part Return type: str
- classmethod get_url_parts()¶
Return a list of possible URL specifications
Examples : list, detail/(?P<pk>\d+)
Returns: Compiled URL parts Return type: list
django_crucrudile.urls module¶
Utility functions meant for use in ‘urls.py’, to create URL patterns
- django_crucrudile.urls.auto_patterns_for_app(app_name, exclude_models=None)¶
Returns a list of URL patterns (Django URL objects) for the given application, using content types.
Parameters: - app_name (str) – Application name to get URL patterns for
- exclude_models (list) – Don’t get URL patterns for these models (Specify models by class name)
Raises ImproperlyConfigured: if failing to import django.contrib.contenttypes
Returns: URL patterns for the given application
Return type: list
django_crucrudile.utils module¶
Utility functions¶
This module contains four utility functions, used by other django-crucrudile modules. They are pretty simple, which is why they’re just tossed in here, and not in their own modules.`
This module is imported by views.mixins (for try_calling() and monkeypatch_mixin())and models.mixins (for convert_camel_case()). Should it become any longer, it may be wise to split it.
- django_crucrudile.utils.try_calling(arg, *args, **kwargs)¶
Evaluate and return arg (with given args and kwargs) if it’s a callable, otherwise return None
- django_crucrudile.utils.convert_camel_case(camel_cased, separator)¶
Convert camel cased into words separated by the given separator
Parameters: - camel_cased (str) – Camel cased input string (ex: "CamelCased")
- separator (str) – Separator to use (ex: "-")
Returns: converted text (ex: "camel-cased")
Return type: str
- django_crucrudile.utils.monkeypatch_mixin(class_, mixin)¶
Monkeypatch all non-special (bound and unbound) attributes of mixin into class_, then return class_.
Parameters: - class_ (class) – Class to monkeypatch
- mixin (class) – Mixin to inject in class_
Returns: Monkeypatched class_
Return type: class