How to get a url map in django? [duplicate] - python

Is there a way to get the complete django url configuration?
For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.

Django extensions provides a utility to do this as a manage.py command.
pip install django-extensions
Then add django_extensions to your INSTALLED_APPS in settings.py. then from the console just type the following
python manage.py show_urls

Django is Python, so introspection is your friend.
In the shell, import urls. By looping through urls.urlpatterns, and drilling down through as many layers of included url configurations as possible, you can build the complete url configuration.
import urls
urls.urlpatterns
The list urls.urlpatterns contains RegexURLPattern and RegexURLResolver objects.
For a RegexURLPattern object p you can display the regular expression with
p.regex.pattern
For a RegexURLResolver object q, which represents an included url configuration, you can display the first part of the regular expression with
q.regex.pattern
Then use
q.url_patterns
which will return a further list of RegexURLResolver and RegexURLPattern objects.

At the risk of adding a "me too" answer, I am posting a modified version of the above submitted script that gives you a view listing all the URLs in the project, somewhat prettified and sorted alphabetically, and the views that they call. More of a developer tool than a production page.
def all_urls_view(request):
from your_site.urls import urlpatterns #this import should be inside the function to avoid an import loop
nice_urls = get_urls(urlpatterns) #build the list of urls recursively and then sort it alphabetically
return render(request, "yourapp/links.html", {"links":nice_urls})
def get_urls(raw_urls, nice_urls=[], urlbase=''):
'''Recursively builds a list of all the urls in the current project and the name of their associated view'''
from operator import itemgetter
for entry in raw_urls:
fullurl = (urlbase + entry.regex.pattern).replace('^','')
if entry.callback: #if it points to a view
viewname = entry.callback.func_name
nice_urls.append({"pattern": fullurl,
"location": viewname})
else: #if it points to another urlconf, recur!
get_urls(entry.url_patterns, nice_urls, fullurl)
nice_urls = sorted(nice_urls, key=itemgetter('pattern')) #sort alphabetically
return nice_urls
and the template:
<ul>
{% for link in links %}
<li>
{{link.pattern}} ----- {{link.location}}
</li>
{% endfor%}
</ul>
If you wanted to get real fancy you could render the list with input boxes for any of the regexes that take variables to pass to the view (again as a developer tool rather than production page).

This question is a bit old, but I ran into the same problem and I thought I would discuss my solution. A given Django project obviously needs a means of knowing about all its URLs and needs to be able to do a couple things:
map from a url -> view
map from a named url -> url (then 1 is used to get the view)
map from a view name -> url (then 1 is used to get the view)
Django accomplishes this mostly through an object called a RegexURLResolver.
RegexURLResolver.resolve (map from a url -> view)
RegexURLResolver.reverse
You can get your hands on one of these objects the following way:
from my_proj import urls
from django.core.urlresolvers import get_resolver
resolver = get_resolver(urls)
Then, you can simply print out your urls the following way:
for view, regexes in resolver.reverse_dict.iteritems():
print "%s: %s" % (view, regexes)
That said, Alasdair's solution is perfectly fine and has some advantages, as it prints out some what more nicely than this method. But knowing about and getting your hands on a RegexURLResolver object is something nice to know about, especially if you are interested in Django internals.

The easiest way to get a complete list of registered URLs is to install contrib.admindocs then check the "Views" section. Very easy to set up, and also gives you fully browsable docs on all of your template tags, models, etc.

I have submitted a package (django-showurls) that adds this functionality to any Django project, it's a simple new management command that integrates well with manage.py:
$ python manage.py showurls
^admin/
^$
^login/$
^logout/$
.. etc ..
You can install it through pip:
pip install django-showurls
And then add it to your installed apps in your Django project settings.py file:
INSTALLED_APPS = [
..
'django_showurls',
..
]
And you're ready to go.
More info here -
https://github.com/Niklas9/django-showurls

If you want a list of all the urls in your project, first you need to install django-extensions
You can simply install using command.
pip install django-extensions
For more information related to package goto django-extensions
After that, add django_extensions in INSTALLED_APPS in your settings.py file like this:
INSTALLED_APPS = (
...
'django_extensions',
...
)
urls.py example:
from django.urls import path, include
from . import views
from . import health_views
urlpatterns = [
path('get_url_info', views.get_url_func),
path('health', health_views.service_health_check),
path('service-session/status', views.service_session_status)
]
And then, run any of the command in your terminal
python manage.py show_urls
or
./manage.py show_urls
Sample output example based on config urls.py:
/get_url_info django_app.views.get_url_func
/health django_app.health_views.service_health_check
/service-session/status django_app.views.service_session_status
For more information you can check the documentation.

Are you looking for the urls evaluated or not evaluated as shown in the DEBUG mode? For evaluated, django.contrib.sitemaps can help you there, otherwise it might involve some reverse engineering with Django's code.

When I tried the other answers here, I got this error:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
It looks like the problem comes from using django.contrib.admin.autodiscover() in my urls.py, so I can either comment that out, or load Django properly before dumping the URL's. Of course if I want to see the admin URL's in the mapping, I can't comment them out.
The way I found was to create a custom management command that dumps the urls.
# install this file in mysite/myapp/management/commands/urldump.py
from django.core.management.base import BaseCommand
from kive import urls
class Command(BaseCommand):
help = "Dumps all URL's."
def handle(self, *args, **options):
self.show_urls(urls.urlpatterns)
def show_urls(self, urllist, depth=0):
for entry in urllist:
print ' '.join((" " * depth, entry.regex.pattern,
entry.callback and entry.callback.__module__ or '',
entry.callback and entry.callback.func_name or ''))
if hasattr(entry, 'url_patterns'):
self.show_urls(entry.url_patterns, depth + 1)

If you are running Django in debug mode (have DEBUG = True in your settings) and then type a non-existent URL you will get an error page listing the complete URL configuration.

Related

Adding a variable into a a path in django

I am making my first website in Django but my tutorial was created long ago. I need to add the variable question_id into the following path:
path('<question_id [0-9]>/',views.detail, name = "detail")
the function detail looks like this:
def detail(request, question_id):
return HttpResponse('Leo is the best')
This is what the error looks like:
Using the URLconf defined in mysite.urls, Django tried these URL
patterns, in this order:
polls/ [name='index']
polls/ <question_id = [0-9]>/ [name='detail']
polls/ <question_id>[0-9]/result [name='result']
polls/ <question_id>[0-9]/vote [name='vote']
Firstly, rather than using a tutorial "created a long time ago", you should use the actual tutorial for your Django version.
The code you have used in your URLs is neither valid for the old regex-based routing nor for the new-style path routing. The new style is easier, you should probably just use that:
path('<int:question_id>/',views.detail, name = "detail")
Use r'^<question_id [0-9]>$' instead of <question_id [0-9]>/ and as far as I know, correct syntax for Django is url(r'^<question_id [0-9]>$',views.detail, name = "detail") not path.
Not sure but you should use url() not path()

save() doesn't work in Mongoengine

I'm trying to perform a simple insert operation using Mongoengine and Django.
Regarding my project structure simply I have a project, AProject and an app, AnApp. I have a running mongo in a remote machine with an IP of X.X.X.X. I am able to insert document using Robomongo in it.
I have removed the default Database configuration part of the settings.py located inside the AProject directory. The newly added lines are shown below:
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
import mongoengine
# ----------- MongoDB stuff
from mongoengine import register_connection
register_connection(alias='default', name='AProject', host='X.X.X.X')
# ----------
Now let me show the models.py and the views.py located inside AnApp.
models.py
from mongoengine import Document, StringField
class Confession(Document):
confession = StringField(required=True)
views.py
from django.http import HttpResponse
from models import Confession
from mongoengine import connect
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession()
confession.confession = 'First confession from the API'
print(confession.confession + ' Printable') # The output is --First confession from the API Printable--
print(confession.save()) # The output is --Confession object--
return HttpResponse(request)
The urls.py located inside AProject is simply as below:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^confessions/', include('confession.urls')),
url(r'^admin/', admin.site.urls),
]
When I enter http://127.0.0.1:10000/confessions/ I see a blank screen which I expect. However there is nothing saved from the API. I get the expected output except Confession object.
How can I solve this problem?
EDIT:
I found the concrete proof that currently MongoEngine's support for Django is unstable and it is corresponding to Django version 1.9:
MongoEngine documentation on Django support states:
Django support has been split from the main MongoEngine repository. The legacy Django extension may be found bundled with the 0.9 release of MongoEngine.
and
6.1. Help Wanted!
The MongoEngine team is looking for help contributing and maintaining a new Django extension for MongoEngine! If you have Django experience and would like to help contribute to the project, please get in touch on the mailing list or by simply contributing on GitHub.
Which leads to this repo, where the following is stated:
THIS IS UNSTABLE PROJECT, IF YOU WANT TO USE IT - FIX WHAT YOU NEED
Right now we're targeting to get things working on Django 1.9
So it may be possible that it cannot play well with Django at this state or with your version and thus the problem occurs.
Initial attempt, leaving it here for legacy reasons.
I believe that the problem occurs on how you are initializing your object, although I do not have a set up to test this theory.
It is generally considered that is better to make a new object with the .create() method:
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession.objects.create(
confession='First confession from the API'
)
print(confession.confession + ' Printable')
confession.save()
return HttpResponse(request)
Have a look at the Django & MongoDB tutorial for more details.
In this tutorial, the supported Django version is not mentioned, but I haven't found concrete proof that MongoDB Engine can or can't play well with Django version > 1.8.
Good luck :)

Changing Site Name in Django 1.9

I am currently following a tutorial which introduces a custom Bootstrap 3 template and builds a Django site using it. In the tutorial they suggest that one changes the following template snippet:
<a class="navbar-brand" href="index.html">Start Bootstrap</a>
to the following snippet.
<a class="navbar-brand" href="/">{{ request.site.name }}</a>
However, when I make this change, no site name shows. I am wondering where I should be setting this name. If it helps, I am using Django CMS and there is only one site called example.compopulated in the Sites section of the Administration.
Had the same problem, found this in the documentation.
If you often use this pattern:
from django.contrib.sites.models import Site
def my_view(request):
site = Site.objects.get_current()
... there is simple way to avoid repetitions. Add django.contrib.sites.middleware.CurrentSiteMiddleware to MIDDLEWARE_CLASSES. The middleware sets the site attribute on every request object, so you can use request.site to get the current site.
You can add site name or change existing site called example.com in the Sites section of the Administration.
To access Site object you need to provide SITE_ID in your settings.py
If you are changing example.com then use SITE_ID = 1 in settings
To render site name in django templates, get value from site model using
from django.contrib.sites.models import Site
current_domain = Site.objects.get_current().domain
then pass current_domain to template
It seems that you have to enable the sites framework, refer to doc.
first yo have to understand that in the setting you have a site_id set to 1 and in database migrations an example site with domain name example.com is created. So, you have two options:
You can change this default from django site models like this: python manage.py shell -c "from django.contrib.sites.models import Site; Site.objects.filter(domain='example.com').update(name='My Site', domain='mysite.tld')" then you restart the server.
You can insert a new row in the site models like this: python manage.py shell -c "from django.contrib.sites.models import Site; mysite,_=Site.objects.get_or_create(id=101, name='mysite.tld', domain='mysite.tld'); print(mysite.id, mysite.name)" Then change the site_id in the settings to the new site_id which should be 2 since it is the second new row.
You can take a look at this Github trend for more clearity.

Django Middleware: Can't get urlredirect to work

So I'm very new to Django, but have completed the tutorials on (https://docs.djangoproject.com/en/1.4/intro/tutorial01/) several times and feel that I'm getting a pretty good handle on it.
The next item I'd like to tackle is creating , installing and configuring middleware (more specifically i'm trying to make it so that when local host accesses the site that it pulls up fine and when someone other than local host pulls it up that it forwards to google.com or some other random site.) I'm mainly doing this for experience building at the request of my boss, so any help would be greatly appreciated! :)
I've read the following sites, but can't seem to figure out what to do to get the url redirect to work.
$https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs
$https://docs.djangoproject.com/en/dev/ref/middleware/
$http://djangosnippets.org/snippets/510/
Code that I've picked up from the above site (www.djangosnippets.org)
import re
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
class UrlRedirectMiddleware:
"""
This middleware lets you match a specific url and redirect the request to a
new url.
You keep a tuple of url regex pattern/url redirect tuples on your site
settings, example:
URL_REDIRECTS = (
(r'www\.example\.com/hello/$', 'http://hello.example.com/'),
(r'www\.example2\.com/$', 'http://www.example.com/example2/'),
)
"""
def process_request(self, request):
host = request.META['HTTP_HOST'] + request.META['PATH_INFO']
for url_pattern, redirect_url in settings.URL_REDIRECTS:
regex = re.compile(url_pattern)
if regex.match(host):
return HttpResponsePermanentRedirect(redirect_url)
Add to your settings (assuming you are working with the development server):
e.g
URL_REDIRECTS = (
(r'127.0.0.1:8000/hello', 'http://www.google.com'),
)
Also add the UrlRedirectMiddleware python-path to your MIDDLEWARE_CLASSES in your settings.
e.g if your UrlRedirectMiddleware is defined in a module called my_middle.py inside an application called app
add 'app.my_middle.UrlRedirectMiddleware' to your MIDDLEWARE_CLASSES

Defining Constants in Django

I want to have some constants in a Django Projects. For example, let's say a constant called MIN_TIME_TEST.
I would like to be able to access this constant in two places: from within my Python code, and from within any Templates.
What's the best way to go about doing this?
EDIT:
To clarify, I know about Template Context Processors and about just putting things in settings.py or some other file and just importing.
My question is, how do I combine the two approaches without violating the "Don't Repeat Yourself" rule? Based on the answers so far, here's my approach:
I'd like to create a file called global_constants.py, which will have a list of constants (things like MIN_TIME_TEST = 5). I can import this file into any module to get the constants.
But now, I want to create the context processor which returns all of these constants. How can I go about doing this automatically, without having to list them again in a dictionary, like in John Mee's answer?
Both Luper and Vladimir are correct imho but you'll need both in order to complete your requirements.
Although, the constants don't need to be in the settings.py, you could put them anywhere and import them from that place into your view/model/module code. I sometimes put them into the __init__.py if I don't care to have them to be considered globally relevant.
a context processor like this will ensure that selected variables are globally in the template scope
def settings(request):
"""
Put selected settings variables into the default template context
"""
from django.conf import settings
return {
'DOMAIN': settings.DOMAIN,
'GOOGLEMAPS_API_KEY': settings.GOOGLEMAPS_API_KEY,
}
But this might be overkill if you're new to django; perhaps you're just asking how to put variables into the template scope...?
from django.conf import settings
...
# do stuff with settings.MIN_TIME_TEST as you wish
render_to_response("the_template.html", {
"MIN_TIME_TEST": settings.MIN_TIME_TEST
}, context_instance=RequestContext(request)
To build on other people's answers, here's a simple way you'd implement this:
In your settings file:
GLOBAL_SETTINGS = {
'MIN_TIME_TEST': 'blah',
'RANDOM_GLOBAL_VAR': 'blah',
}
Then, building off of John Mee's context processor:
def settings(request):
"""
Put selected settings variables into the default template context
"""
from django.conf import settings
return settings.GLOBAL_SETTINGS
This will resolve the DRY issue.
Or, if you only plan to use the global settings occasionally and want to call them from within the view:
def view_func(request):
from django.conf import settings
# function code here
ctx = {} #context variables here
ctx.update(settings.GLOBAL_SETTINGS)
# whatever output you want here
Consider putting it into settings.py of your application. Of course, in order to use it in template you will need to make it available to template as any other usual variable.
Use context processors to have your constants available in all templates (settings.py is a nice place to define them as Vladimir said).
Context processors are better suited at handling more dynamic object data--they're defined as a mapping in the documentation and in many of the posts here they're being modified or passed around to views--it doesn't make sense that a template may lose access to global information because, for example, your forgot to use a specialized context processor in the view. The data is global by definition & that couples the view to the template.
A better way is to define a custom template tag. This way:
templates aren't relying on views to have global information passed into them
it's DRY-er: the app defining the global settings can be exported to many projects, eliminating common code across projects
templates decide whether they have access to the global information, not the view functions
In the example below I deal with your problem--loading in this MIN_TIME_TEST variable--and a problem I commonly face, loading in URLs that change when my environment changes.
I have 4 environments--2 dev and 2 production:
Dev: django-web server, url: localhost:8000
Dev: apache web server: url: sandbox.com -> resolves to 127.0.0.1
Prod sandbox server, url: sandbox.domain.com
Prod server: url: domain.com
I do this on all my projects & keep all the urls in a file, global_settings.py so it's accessible from code. I define a custom template tag {% site_url %} that can be (optionally) loaded into any template
I create an app called global_settings, and make sure it's included in my settings.INSTALLED_APPS tuple.
Django compiles templated text into nodes with a render() method that tells how the data should be displayed--I created an object that renders data by returnning values in my global_settings.py based on the name passed in.
It looks like this:
from django import template
import global_settings
class GlobalSettingNode(template.Node):
def __init__(self, settingname):
self.settingname = settingname;
def render(self, context):
if hasattr(global_settings, self.settingname):
return getattr(global_settings, self.settingname)
else:
raise template.TemplateSyntaxError('%s tag does not exist' % self.settingname)
Now, in global_settings.py I register a couple tags: site_url for my example and min_test_time for your example. This way, when {% min_time_test %} is invoked from a template, it'll call get_min_time_test which resolves to load in the value=5. In my example, {% site_url %} will do a name-based lookup so that I can keep all 4 URLs defined at once and choose which environment I'm using. This is more flexible for me than just using Django's built in settings.Debug=True/False flag.
from django import template
from templatenodes import GlobalSettingNode
register = template.Library()
MIN_TIME_TEST = 5
DEV_DJANGO_SITE_URL = 'http://localhost:8000/'
DEV_APACHE_SITE_URL = 'http://sandbox.com/'
PROD_SANDBOX_URL = 'http://sandbox.domain.com/'
PROD_URL = 'http://domain.com/'
CURRENT_ENVIRONMENT = 'DEV_DJANGO_SITE_URL'
def get_site_url(parser, token):
return GlobalSettingNode(CURRENT_ENVIRONMENT)
def get_min_time_test(parser, token):
return GlobalSettingNode('MIN_TIME_TEST')
register.tag('site_url', get_site_url)
register.tag('min_time_test', get_min_time_test)
Note that for this to work, django is expecting global_settings.py to be located in a python packaged called templatetags under your Django app. My Django app here is called global_settings, so my directory structure looks like:
/project-name/global_settings/templatetags/global_settings.py
etc.
Finally the template chooses whether to load in global settings or not, which is beneficial for performance. Add this line to your template to expose all the tags registered in global_settings.py:
{% load global_settings %}
Now, other projects that need MIN_TIME_TEST or these environments exposed can simply install this app =)
In the context processor you can use something like:
import settings
context = {}
for item in dir(settings):
#use some way to exclude __doc__, __name__, etc..
if item[0:2] != '__':
context[item] = getattr(settings, item)
Variant on John Mee's last part, with a little elaboration on the same idea Jordan Reiter discusses.
Suppose you have something in your settings akin to what Jordan suggested -- in other words, something like:
GLOBAL_SETTINGS = {
'SOME_CONST': 'thingy',
'SOME_OTHER_CONST': 'other_thingy',
}
Suppose further you already have a dictionary with some of the variables you'd like to pass your template, perhaps passed as arguments to your view. Let's call it my_dict. Suppose you want the values in my_dict to override those in the settings.GLOBAL_SETTINGS dictionary.
You might do something in your view like:
def my_view(request, *args, **kwargs)
from django.conf import settings
my_dict = some_kind_of_arg_parsing(*args,**kwargs)
tmp = settings.GLOBAL_SETTINGS.copy()
tmp.update(my_dict)
my_dict = tmp
render_to_response('the_template.html', my_dict, context_instance=RequestContext(request))
This lets you have the settings determined globally, available to your templates, and doesn't require you to manually type out each of them.
If you don't have any additional variables to pass the template, nor any need to override, you can just do:
render_to_response('the_template.html', settings.GLOBAL_SETTINGS, context_instance=RequestContext(request))
The main difference between what I'm discussing here & what Jordan has, is that for his, settings.GLOBAL_SETTINGS overrides anything it may have in common w/ your context dictionary, and with mine, my context dictionary overrides settings.GLOBAL_SETTINGS. YMMV.

Categories