PageRenderTime 404ms CodeModel.GetById 221ms app.highlight 6ms RepoModel.GetById 175ms app.codeStats 0ms

/django/contrib/contenttypes/management.py

https://code.google.com/p/mango-py/
Python | 60 lines | 53 code | 1 blank | 6 comment | 9 complexity | f87ecd808c4d1678961f485f0e0cd04c MD5 | raw file
 1from django.contrib.contenttypes.models import ContentType
 2from django.db.models import get_apps, get_models, signals
 3from django.utils.encoding import smart_unicode
 4
 5def update_contenttypes(app, created_models, verbosity=2, **kwargs):
 6    """
 7    Creates content types for models in the given app, removing any model
 8    entries that no longer have a matching model class.
 9    """
10    ContentType.objects.clear_cache()
11    content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2]))
12    app_models = get_models(app)
13    if not app_models:
14        return
15    for klass in app_models:
16        opts = klass._meta
17        try:
18            ct = ContentType.objects.get(app_label=opts.app_label,
19                                         model=opts.object_name.lower())
20            content_types.remove(ct)
21        except ContentType.DoesNotExist:
22            ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
23                app_label=opts.app_label, model=opts.object_name.lower())
24            ct.save()
25            if verbosity >= 2:
26                print "Adding content type '%s | %s'" % (ct.app_label, ct.model)
27    # The presence of any remaining content types means the supplied app has an
28    # undefined model. Confirm that the content type is stale before deletion.
29    if content_types:
30        if kwargs.get('interactive', False):
31            content_type_display = '\n'.join(['    %s | %s' % (ct.app_label, ct.model) for ct in content_types])
32            ok_to_delete = raw_input("""The following content types are stale and need to be deleted:
33
34%s
35
36Any objects related to these content types by a foreign key will also
37be deleted. Are you sure you want to delete these content types?
38If you're unsure, answer 'no'.
39
40    Type 'yes' to continue, or 'no' to cancel: """ % content_type_display)
41        else:
42            ok_to_delete = False
43
44        if ok_to_delete == 'yes':
45            for ct in content_types:
46                if verbosity >= 2:
47                    print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model)
48                ct.delete()
49        else:
50            if verbosity >= 2:
51                print "Stale content types remain."
52
53def update_all_contenttypes(verbosity=2, **kwargs):
54    for app in get_apps():
55        update_contenttypes(app, None, verbosity, **kwargs)
56
57signals.post_syncdb.connect(update_contenttypes)
58
59if __name__ == "__main__":
60    update_all_contenttypes()