webentwicklung-frage-antwort-db.com.de

Django: Wie kann ich eine Liste von URL-Mustern sehen?

Wie kann ich die aktuellen URL-Muster sehen, die "Reverse" sucht? 

Ich rufe in einer Ansicht umgekehrt mit einem Argument auf, das meiner Meinung nach funktionieren sollte, aber nicht funktioniert. Wie kann ich überprüfen, was da ist und warum mein Muster nicht ist?

69
interstar

Wenn Sie eine Liste aller URLs in Ihrem Projekt erhalten möchten, müssen Sie zunächst Django-Erweiterungen installieren und diese wie folgt zu Ihren Einstellungen hinzufügen:

INSTALLED_APPS = (
...
'Django_extensions',
...
)

Führen Sie dann diesen Befehl in Ihrem Terminal aus

./manage.py show_urls

Für weitere Informationen können Sie überprüfen Sie die Dokumentation.

110
robert

Versuche dies:

from Django.core.urlresolvers import get_resolver
get_resolver(None).reverse_dict.keys()
51
SmileyChris

Es gibt ein Rezept auf activestate

import urls

def show_urls(urllist, depth=0):
    for entry in urllist:
        print("  " * depth, entry.regex.pattern)
        if hasattr(entry, 'url_patterns'):
            show_urls(entry.url_patterns, depth + 1)

show_urls(urls.url_patterns)
14
pmav99

Ich benutze den nächsten Befehl:

(Python3 + Django 1.10)

from Django.core.management import BaseCommand
from Django.conf.urls import RegexURLPattern, RegexURLResolver
from Django.core import urlresolvers


class Command(BaseCommand):

    def add_arguments(self, parser):

        pass

    def handle(self, *args, **kwargs):

        urls = urlresolvers.get_resolver()
        all_urls = list()

        def func_for_sorting(i):
            if i.name is None:
                i.name = ''
            return i.name

        def show_urls(urls):
            for url in urls.url_patterns:
                if isinstance(url, RegexURLResolver):
                    show_urls(url)
                Elif isinstance(url, RegexURLPattern):
                    all_urls.append(url)
        show_urls(urls)

        all_urls.sort(key=func_for_sorting, reverse=False)

        print('-' * 100)
        for url in all_urls:
            print('| {0.regex.pattern:20} | {0.name:20} | {0.lookup_str:20} | {0.default_args} |'.format(url))
        print('-' * 100)

Verwendungszweck:

./manage.py showurls

Beispielausgabe:

----------------------------------------------------------------------------------------------------
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^(.+)/$              |                      | Django.views.generic.base.RedirectView | {} |
| ^static\/(?P<path>.*)$ |                      | Django.contrib.staticfiles.views.serve | {} |
| ^media\/(?P<path>.*)$ |                      | Django.views.static.serve | {'document_root': '/home/wlysenko/.virtualenvs/programmerHelper/project/media'} |
| ^(?P<app_label>polls|snippets|questions)/$ | app_list             | apps.core.admin.AdminSite.app_index | {} |
| ^(?P<app_label>activity|articles|badges|books|comments|flavours|forum|marks|newsletters|notifications|opinions|polls|questions|replies|snippets|solutions|tags|testing|users|utilities|visits)/reports/$ | app_reports          | apps.core.admin.AdminSite.reports_view | {} |
| ^(?P<app_label>activity|articles|badges|books|comments|flavours|forum|marks|newsletters|notifications|opinions|polls|questions|replies|snippets|solutions|tags|testing|users|utilities|visits)/statistics/$ | app_statistics       | apps.core.admin.AdminSite.statistics_view | {} |
| articles/(?P<slug>[-\w]+)/$ | article              | apps.articles.views.ArticleDetailView | {} |
| book/(?P<slug>[-_\w]+)/$ | book                 | apps.books.views.BookDetailView | {} |
| category/(?P<slug>[-_\w]+)/$ | category             | apps.utilities.views.CategoryDetailView | {} |
| create/$             | create               | apps.users.views.UserDetailView | {} |
| delete/$             | delete               | apps.users.views.UserDetailView | {} |
| detail/(?P<email>\[email protected][-_\w]+.\w+)/$ | detail               | apps.users.views.UserDetailView | {} |
| snippet/(?P<slug>[-_\w]+)/$ | detail               | apps.snippets.views.SnippetDetailView | {} |
| (?P<contenttype_model_pk>\d+)/(?P<pks_separated_commas>[-,\w]*)/$ | export               | apps.export_import_models.views.ExportTemplateView | {} |
| download_preview/$   | export_preview_download | apps.export_import_models.views.ExportPreviewDownloadView | {} |
| ^$                   | import               | apps.export_import_models.views.ImportTemplateView | {} |
| result/$             | import_result        | apps.export_import_models.views.ImportResultTemplateView | {} |
| ^$                   | index                | Django.contrib.admin.sites.AdminSite.index | {} |
| ^$                   | index                | apps.core.views.IndexView | {} |
| ^jsi18n/$            | javascript-catalog   | Django.views.i18n.javascript_catalog | {'packages': ('your.app.package',)} |
| ^jsi18n/$            | jsi18n               | Django.contrib.admin.sites.AdminSite.i18n_javascript | {} |
| level/(?P<slug>[-_\w]+)/$ | level                | apps.users.views.UserDetailView | {} |
| ^login/$             | login                | Django.contrib.admin.sites.AdminSite.login | {} |
| ^logout/$            | logout               | Django.contrib.admin.sites.AdminSite.logout | {} |
| newsletter/(?P<slug>[_\w]+)/$ | newsletter           | apps.newsletters.views.NewsletterDetailView | {} |
| newsletters/$        | newsletters          | apps.newsletters.views.NewslettersListView | {} |
| notification/(?P<account_email>[-\w][email protected][-\w]+.\w+)/$ | notification         | apps.notifications.views.NotificationDetailView | {} |
| ^password_change/$   | password_change      | Django.contrib.admin.sites.AdminSite.password_change | {} |
| ^password_change/done/$ | password_change_done | Django.contrib.admin.sites.AdminSite.password_change_done | {} |
| ^image/(?P<height>\d+)x(?P<width>\d+)/$ | placeholder          | apps.core.views.PlaceholderView | {} |
| poll/(?P<pk>\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/(?P<slug>[-\w]+)/$ | poll                 | apps.polls.views.PollDetailView | {} |
| ^add/$               | polls_choice_add     | Django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | polls_choice_change  | Django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | polls_choice_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | polls_choice_delete  | Django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | polls_choice_history | Django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^add/$               | polls_poll_add       | Django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | polls_poll_change    | Django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | polls_poll_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | polls_poll_delete    | Django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | polls_poll_history   | Django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^$                   | polls_vote_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| publisher/(?P<slug>[-_\w]+)/$ | publisher            | apps.books.views.PublisherDetailView | {} |
| question/(?P<slug>[-_\w]+)/$ | question             | apps.questions.views.QuestionDetailView | {} |
| ^add/$               | questions_answer_add | Django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | questions_answer_change | Django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | questions_answer_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | questions_answer_delete | Django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | questions_answer_history | Django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^add/$               | questions_question_add | Django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | questions_question_change | Django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | questions_question_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | questions_question_delete | Django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | questions_question_history | Django.contrib.admin.options.ModelAdmin.history_view | {} |
| ^setlang/$           | set_language         | Django.views.i18n.set_language | {} |
| ^add/$               | snippets_snippet_add | Django.contrib.admin.options.ModelAdmin.add_view | {} |
| ^(.+)/change/$       | snippets_snippet_change | Django.contrib.admin.options.ModelAdmin.change_view | {} |
| ^$                   | snippets_snippet_changelist | Django.contrib.admin.options.ModelAdmin.changelist_view | {} |
| ^(.+)/delete/$       | snippets_snippet_delete | Django.contrib.admin.options.ModelAdmin.delete_view | {} |
| ^(.+)/history/$      | snippets_snippet_history | Django.contrib.admin.options.ModelAdmin.history_view | {} |
| solution/(?P<pk>\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/(?P<slug>[-_\w]+)/$ | solution             | apps.solutions.views.SolutionDetailView | {} |
| suit/(?P<slug>[-\w]+)/$ | suit                 | apps.testing.views.SuitDetailView | {} |
| tag/(?P<name>[-_\w]+)/$ | tag                  | apps.tags.views.TagDetailView | {} |
| theme/(?P<slug>[-_\w]+)/$ | theme                | apps.forum.views.SectionDetailView | {} |
| topic/(?P<slug>[-_\w]+)/$ | topic                | apps.forum.views.TopicDetailView | {} |
| update/$             | update               | apps.users.views.UserDetailView | {} |
| ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ | view_on_site         | Django.contrib.contenttypes.views.shortcut | {} |
| writer/(?P<slug>[-_\w]+)/$ | writer               | apps.books.views.WriterDetailView | {} |
----------------------------------------------------------------------------------------------------
13
Seti Volkylany

Django 1.11, Python 2.7.6

cd to_your_Django_project

python manage.py Shell

Fügen Sie dann folgenden Code ein.

from Django.conf.urls import RegexURLPattern, RegexURLResolver
from Django.core import urlresolvers
urls = urlresolvers.get_resolver()

def if_none(value):
    if value:
        return value
    return ''

def print_urls(urls, parent_pattern=None):
    for url in urls.url_patterns:
        if isinstance(url, RegexURLResolver):
            print_urls(url, if_none(parent_pattern) + url.regex.pattern)
        Elif isinstance(url, RegexURLPattern):
            print if_none(parent_pattern) + url.regex.pattern

print_urls(urls)

Beispielausgabe:

^Django-admin/^$
^Django-admin/^login/$
^Django-admin/^logout/$
^Django-admin/^password_change/$
^Django-admin/^password_change/done/$
^Django-admin/^jsi18n/$
^Django-admin/^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$
^Django-admin/^wagtailimages/image/^$
^Django-admin/^wagtailimages/image/^add/$
^Django-admin/^wagtailimages/image/^(.+)/history/$
^Django-admin/^wagtailimages/image/^(.+)/delete/$
^Django-admin/^wagtailimages/image/^(.+)/change/$
^Django-admin/^wagtailimages/image/^(.+)/$
...
8
small mammal

Es gibt ein Plugin, das ich benutze: https://github.com/Django-extensions/Django-extensions .

5
imjoevasquez
def get_resolved_urls(url_patterns):
    url_patterns_resolved = []
    for entry in url_patterns:
        if hasattr(entry, 'url_patterns'):
            url_patterns_resolved += get_resolved_urls(
                entry.url_patterns)
        else:
            url_patterns_resolved.append(entry)
    return url_patterns_resolved

In python manage.py Shell

import urls
get_resolved_urls(urls.urlpatterns)
3
Sandeep

Ich habe Setis Befehl erweitert, um den Namespace, alle URL-Teile anzuzeigen, Spaltenbreiten automatisch anzupassen, sortiert nach (Namespace, Name): https://Gist.github.com/andreif/263a3fa6e7c425297ffee09c25f66b20

import sys
from Django.core.management import BaseCommand
from Django.conf.urls import RegexURLPattern, RegexURLResolver
from Django.core import urlresolvers


def collect_urls(urls=None, namespace=None, prefix=None):
    if urls is None:
        urls = urlresolvers.get_resolver()
    _collected = []
    prefix = prefix or []
    for x in urls.url_patterns:
        if isinstance(x, RegexURLResolver):
            _collected += collect_urls(x, namespace=x.namespace or namespace,
                                       prefix=prefix + [x.regex.pattern])
        Elif isinstance(x, RegexURLPattern):
            _collected.append({'namespace': namespace or '',
                               'name': x.name or '',
                               'pattern': prefix + [x.regex.pattern],
                               'lookup_str': x.lookup_str,
                               'default_args': dict(x.default_args)})
        else:
            raise NotImplementedError(repr(x))
    return _collected


def show_urls():
    all_urls = collect_urls()
    all_urls.sort(key=lambda x: (x['namespace'], x['name']))

    max_lengths = {}
    for u in all_urls:
        for k in ['pattern', 'default_args']:
            u[k] = str(u[k])
        for k, v in list(u.items())[:-1]:
            # Skip app_list due to length (contains all app names)
            if (u['namespace'], u['name'], k) == \
                    ('admin', 'app_list', 'pattern'):
                continue
            max_lengths[k] = max(len(v), max_lengths.get(k, 0))

    for u in all_urls:
        sys.stdout.write(' | '.join(
            ('{:%d}' % max_lengths.get(k, len(v))).format(v)
            for k, v in u.items()) + '\n')


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        show_urls()

Hinweis: Die Reihenfolge der -Spalten wird in Python 3.6 beibehalten, und in älteren Versionen müsste OrderedDict verwendet werden.

Update: Eine neue Version mit OrderedDict wohnt jetzt in Django - ???? s Paket: https://github.com/5monkeys/Django-bananas/blob/master/bananas/management/commands/show_urls .py

3
Andrei

Geben Sie einfach eine URL ein, von der Sie wissen, dass sie nicht existiert, und der Server gibt eine Fehlermeldung mit einer Liste von URL-Mustern zurück. 

Wenn Sie beispielsweise eine Site unter http: // localhost: 8000/etwas betreiben,

Eintippen

http: // localhost: 8000/etwas/blahNonsense , und Ihr Server gibt die URL-Suchliste zurück und zeigt sie im Browser an

2
JHRS

Minimalistische Lösung für Django 2.0

Wenn Sie beispielsweise nach einer URL suchen, die in der ersten App von installed_apps enthalten ist, können Sie folgendermaßen darauf zugreifen:

from Django.urls import get_resolver
from pprint import pprint

pprint(
    get_resolver().url_patterns[0].url_patterns
)

Django> = 2.0 Lösung

Ich habe die anderen Antworten in diesem Beitrag getestet und sie arbeiteten entweder nicht mit Django 2.X, waren unvollständig oder zu komplex. Deshalb hier meine Meinung dazu:

from Django.conf import settings
from Django.urls import URLPattern, URLResolver

urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])

def list_urls(lis, acc=None):
    if acc is None:
        acc = []
    if not lis:
        return
    l = lis[0]
    if isinstance(l, URLPattern):
        yield acc + [str(l.pattern)]
    Elif isinstance(l, URLResolver):
        yield from list_urls(l.url_patterns, acc + [str(l.pattern)])

    yield from list_urls(lis[1:], acc)


for p in list_urls(urlconf.urlpatterns):
    print(''.join(p))

Dieser Code druckt alle URLs. Im Gegensatz zu anderen Lösungen wird der vollständige Pfad und nicht nur der letzte Knoten gedruckt. z.B.:

admin/
admin/login/
admin/logout/
admin/password_change/
admin/password_change/done/
admin/jsi18n/
admin/r/<int:content_type_id>/<path:object_id>/
admin/auth/group/
admin/auth/group/add/
admin/auth/group/autocomplete/
admin/auth/group/<path:object_id>/history/
admin/auth/group/<path:object_id>/delete/
admin/auth/group/<path:object_id>/change/
admin/auth/group/<path:object_id>/
admin/auth/user/<id>/password/
admin/auth/user/
...
0
Cesar Canassa