- Author:
- dimkoug
- Posted:
- April 6, 2018
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
Create dynamic urlpatterns for classed based views
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | from importlib import import_module
from django.apps import apps
from django.urls import path
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
def get_patterns(app_name, filename):
app_module = import_module('{}.{}'.format(app_name, filename))
app_models = apps.get_app_config(app_name).get_models()
model_names = [model.__name__ for model in app_models]
patterns = []
views = []
for model in model_names:
for key, value in app_module.__dict__.items():
if isinstance(value, type):
if value.__name__.startswith(model):
views.append({key: value})
_views = set()
for key in views:
for key, value in key.items():
for model_name in model_names:
if value.__name__.startswith(model_name) and\
value.__name__ not in _views:
if isinstance(value, type):
if issubclass(value, ListView):
patterns += [path('{}/'.format(
model_name.lower()), value.as_view(),
name='{}-list'.format(model_name.lower()))]
if issubclass(value, DetailView):
patterns += [path('{}/<int:pk>/detail/'.format(
model_name.lower()), value.as_view(),
name='{}-detail'.format(model_name.lower()))]
if issubclass(value, CreateView):
patterns += [path('{}/create/'.format(
model_name.lower()), value.as_view(),
name='{}-create'.format(model_name.lower()))]
if issubclass(value, UpdateView):
patterns += [path('{}/<int:pk>/update/'.format(
model_name.lower()), value.as_view(),
name='{}-update'.format(model_name.lower()))]
if issubclass(value, DeleteView):
patterns += [path('{}/<int:pk>/delete/'.format(
model_name.lower()), value.as_view(),
name='{}-delete'.format(model_name.lower()))]
_views.add(value.__name__)
return patterns
# projects is the app name
# views is the filename with the classbased views of your app
urlpatterns = get_patterns('projects', 'views')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.