Adding a variable into a a path in django - python

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()

Related

URL pattern in django to match limited set of words

I have a URL pattern in Django where there is a variable (called name) that should only take one of a select list of words. Something like this:
path("profile/<marta|jose|felipe|manuela:name>/", views.profile),
So basically only these paths are valid:
profile/marta/
profile/jose/
profile/felipe/
profile/manuela/
How exactly can I configure this in the Django url patterns? The above syntax tries to illustrate the idea but doesn't work. I've seen this ten year old question but that uses the previous format in the url patterns file so I imagine it should be done differently now...?
Why not put them in view?
from django.http import Http404
def profiles(request, name):
if not name in ['marta', 'jose', 'felipe', 'manuela']:
raise Http404('You shall not pass!')
Or you can simply use re_path:
urlpatterns = [
re_path(r'^profile/(?P<name>marta|jose|felipe|manuela)/$', views.index, name='index'),
]

Django optional parameter is not readed from url

I was reading the thread Django optional url parameters
And following the steps to generate a URL with a single optional parameter.
Well, my URL should be:
/client/
/client/?clientname=John
And I have defined two urlpatterns
url(r'^$', views.index, name='index'),
url(r'^/(?P<clientname>\d+)/',views.index),
Well, at this point both of them render the page.
But, in my view:
def index(request, clientname='noparameter'):
print("The searched name is: " + str(clientname))
The searched name is always noparameter
Am I doing something wrong?
Url you are having is
/client/John/
instead of
/client/?clientname=John
also even in the following example using John will fail as your regex is for digits , check out more on topic of django dispatcher
/client/4/
if you want to get GET parameters instead you can do that in view by using the following
request.GET.get('clientanme', None)
It seems as though you are getting confused between a keyword argument and a get request. Using keyword arguments, which your urls.py is configured for, your view would like this:
def index(request, **kwargs):
clientname = kwargs.get("clientname", "noparameter")
print("The searched name is: " + str(clientname))
Your urls.py would also have to change to this for the url to this:
url(r'^client/(?P<clientname>\w+)/',views.index),
This could be called in the browser like:
/client/John

Django url with prefix - not working correctly

I am using Django 1.7 with Mezzanine.
URL of my pages has a prefix www.example.com/example
So I use:
FORCE_SCRIPT_NAME = '/example'
It works for default pages like blog. Blog has set url blog and it goes to /example/blog. But if I create custom link (for example in admin), it does not work. It skip /example in URL and goes directly to /.
How to fix that?
Did you wrote the pattern in urls.py?
something like this:
urlpatterns = patterns('',
url(r"^example/$",HandlingClass.as_view(),name='example'),)
Finally I found a solution.
I added FORCE_SCRIPT_NAME into TEMPLATE_ACCESSIBLE_SETTINGS in settings.py. So it is look like that now:
TEMPLATE_ACCESSIBLE_SETTINGS = ('FORCE_SCRIPT_NAME', 'ACCOUNTS_APPROVAL_REQUIRED', 'ACCOUNTS_VERIFICATION_REQUIRED', 'ADMIN_MENU_COLLAPSED', 'BITLY_ACCESS_TOKEN', 'BLOG_USE_FEATURED_IMAGE', 'COMMENTS_DISQUS_SHORTNAME', 'COMMENTS_NUM_LATEST', 'COMMENTS_DISQUS_API_PUBLIC_KEY', 'COMMENTS_DISQUS_API_SECRET_KEY', 'COMMENTS_USE_RATINGS', 'DEV_SERVER', 'FORMS_USE_HTML5', 'GRAPPELLI_INSTALLED', 'GOOGLE_ANALYTICS_ID', 'JQUERY_FILENAME', 'LOGIN_URL', 'LOGOUT_URL', 'SITE_TITLE', 'SITE_TAGLINE', 'USE_L10N')
Now is possible to extend the urls in patterns easily:
{{ settings.FORCE_SCRIPT_NAME }}/rest/of/url
Everything works now.

Redirection is leading me to Page not found error in Django

Project urls.py includes app urls. I am using HttpResponseRedirect to get Likes posted on site. I am not trying to call for template so this is why not using render_to_response. My app view is:
def like_article(request, article_id):
if article_id:
a = Article.objects.get(id=article_id)
count = a.likes
count += 1
a.likes = count
a.save()
return HttpResponseRedirect('articles/get/%s' % article_id)
My app urls.py reflects likes redirection like this:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
My parent "articles" HTML file extended from base says:
<p>{{article.likes}} people liked this article</p>
My single article page extended from base.html shows:
<p>Like</p>
Please advise.
You'd better use {% url [name] [parameters] %} in your template while reverse function in your view to create urls.
In your question, I think the problem is the url router doesn't match.
See:
<p>Like</p>
And:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
It seemed the /article prefix doesn't appeared in you url.
Have you mapped the url - articles/get/article_id, i.,e added a similar pattern in urlpatterns (ex: url(r'^get/(?P<article_id>\d+)/$', 'article.views.get_article', name='get_article'),) tuple, to which you redirected the users!
If yes, then have you created a proper view for it!

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

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.

Categories