Login

Automating URLs

Author:
jorjun
Posted:
June 23, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.

 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
# models.py
# - - - - - - - - 
from django.conf.urls.defaults import patterns, url

class Accessor(object):
    @classmethod
    def get_url_patterns(cls):
        model = cls._meta.object_name.lower()
        acc = []
        if 'get' in cls.access:
            acc.append((r'^%s/(?P<id>\d+)/get/$' %model, '%s_get' % model))
            acc.append((r'^%s/page/(?P<page>\d+)/get/$' % model, '%s_page_get' % model))
        if 'new' in cls.access:
            acc.append((r'^%s/new/post/$' % model, '%s_new_post' % model))
            acc.append((r'^%s/new/get/$' % model, '%s_new_get' % model))
        return [url(*p) for p in acc]

    @classmethod
    def get_default_page(cls):
        app = cls._meta.app_label.lower()
        model = cls._meta.object_name.lower()
        return '/%s/%s/page/1/get/' %(app, model)

class Private(Accessor):
    access = ()

class All(Accessor):
    access = ('get', 'new')

class ReadOnly(Accessor):
    access = ('get',)

class Admin(Accessor):
    access = All.access + ('admin',)

# - - - - - - - - 
utils.py
# - - - - - - - - 
from django.contrib.contenttypes.models import ContentType
from django.conf.urls.defaults import patterns


def get_model_paths(app_label):
    urls = []
    for content in ContentType.objects.filter(app_label=app_label):
        model = models.get_model(app_label=content.app_label, model_name=content.model)
        if hasattr(model, 'get_url_patterns'):
            urls.extend(model.get_url_patterns())
    return patterns('myapp.Main.views', *urls)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.