Django admin urlpatterns problems - regex

I'm trying to complete a Django tutorial (https://docs.djangoproject.com/en/dev/intro/tutorial03/) and have run into a problem which, I think, is my understanding of regular expressions and the include() function.
My problematic urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
which, leads me (upon browsing to http://localhost:8000/admin/) to the detail view of polls.urls - the code of which is:
from django.conf.urls import patterns, url
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
I get why it's matching to polls and getting taken through to polls.urls. Any ideas?
Note: when I comment out the url(r'^polls/, include('polls.urls')), line I can see the admin page again
Thanks!

O.K - so I managed to fix this but am not entirely sure how. It was a case of leaving it and working on other problems and when I came back it was fixed! So, things that I changed:
1.) included {% load url from future %} to ensure forward compatibility in my templates
2.) changed the form action in detail.html to <form action="/polls/{{ poll.id }}/vote/" method="post"> (from <form action="{% url 'polls.views.vote' poll.id %}" method="post">
3.) finally, and probably most importantly - sorted my syntax out! In my views.py file I had Return HttpResponseRedirect(reverse('polls_results', args=(p.id,))) and not Return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
I still don't know which did it but, if anybody is in the same position as me, some combination of those 3 will do it!

Related

How to convert Template tags from normal django to the one django-hosts use

I have just added django-hosts to setup subdomains for my site which works perfectly. Next step is just to convert all the normal django URL's in my template to the one django-hosts like.
I know how to link pages , but once I need to add variables to my URL's i'm not sure how to construct the code for it.
Normal django URL that works
{% url 'golemstats:nodeinfo' node.Node_id node.Node|slugify %}
How do I convert that to a URL that django-hosts like? I've tried the following:
{% host_url 'nodeinfo' host 'golemstats' 'node.Node_id' 'node.Node|slugify' %}
hosts.py
from django.conf import settings
from django_hosts import patterns, host
host_patterns = patterns('',
host(r'www', settings.ROOT_URLCONF, name='www'),
host(r'golem', 'golemstats.urls', name='golemstats'),
)
golemstats.urls
from django.urls import path
from . import views
app_name = 'golemstats'
urlpatterns = [
path('', views.index, name='index'),
path('node', views.searchNode, name='searchNode'),
path('node/<nodeid>/<node>', views.nodeinfo, name="nodeinfo"),
path('version-notifier', views.notifierIndex, name="notifier"),
path('ports', views.portScanner, name="portscanner"),
path('scoreboard', views.scoreboard, name="scoreboard"),
path('tools', views.tools, name="tools"),
path('troubleshooting', views.troubleshooting, name="troubleshooting"),
path('network', views.networkOverview, name="networkOverview"),
]
Fixed. have to put arguments after host_url
{% host_url 'nodeinfo' node.Node_id node.Node|slugify host 'golemstats' %}

how to design Django url pattern to avoid 301

I have a project called blog, the url pattern shows below. I want to make the app "posts" to route all the traffic.
Url patterns of them shows below:
#blog/urls.py
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('posts.url', namespace='posts')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#posts/url.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
home,
down,
get_data_by_post,
)
urlpatterns = [
url(r'^$', home, name='down'),
url(r'^api/$', ins_down, name='api'),
url(r'^p/(?P<slug>[-\w]+)/$', get_data_by_post, name='slug'),
]
When enter into home page, the home function in posts.views will generate some links with local data to render index.html.
def home(request):
final = get_local_suggest()
return render(request, "index.html", final)
Some of the code in index.html template likes below:
<a href="p/{{ results.code }}?From=homepage" class="portfolio-link" target="_blank">
So in home page , some links will show there: "http://example.com/p/code?From=homepage
But the tricky question here is that: when I click the url , the console of Django will print 301 like below. In browser, it will redirect from "/p/code" to "/p/code?From=homepage".
Not Found: /p/code [17/Apr/2017 15:05:23] "GET
/p/code?From=homepage HTTP/1.1" 301 0
There are must be something wrong with url pattern design, how to avoid it happened again?
Thanks!
Your url pattern ends with a slash, so your url should as well.
To make sure you always point your urls to the canonical url and avoid redirects, use the {% url %} template tag:
<a href="{% url 'posts:slug' results.code %}?From=homepage" class="portfolio-link" target="_blank">
Here 'slug' is the name of your url, and results.code is an argument to the url.
You can use request.GET.get('From', '') in your views, and clean your url pattern.

Django flaky url (randomly omits WSGIScriptAlias)

My Django site is producing URLs that intermittently omit my WSGIScriptAlias. If I simply print out {% url 'index' %} in my index.html (see my urls.py settings below) I randomly (around 50% of the time) get either:
MySiteAlias/MySite
which is correct, or
MySite/
which is incorrect.
myapp/urls.py:
from django.conf.urls import url,include
urlpatterns = [
url(r'^MySite/', include('mysite.urls')),
]
mysite/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
and views.index basically does return render(request, 'mysite/index.html). Any ideas on how to fix this?
I'd imagine you might have two urls with the same name, this is where namespaces will help. If you provide a namespace for your mysite.urls then there is no confusion on where you should go to
url(r'^MySite/', include('mysite.urls', namespace='mysite')),
{% url 'mysite:index' %}

Django {% url %} behaving strangely

Can someone explain why this works:
<li>HOME</li>
<li>PROJECTS</li>
While this doesn't:
<li>HOME</li>
<li>PROJECTS</li>
I get a 500 error with ImportError at /index/ No module named project however I'm not trying to import project anywhere. (I am importing Project, which has been importing fine for days, and works fine when I don't use {% url %} style links). I've seen a number of answers here and blog posts elsewhere suggesting that {% url %} is a bad idea. I'm happy to stop using them if necessary, but for the life of me can't see where the error is coming from.
Contents of urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.static import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^index/', 'projects.views.index', name='index'),
url(r'^login/', 'project.views.login', name='login'),
url(r'^project/(?P<project_id>\d+)/$', 'projects.views.project', name='project'),
url(r'^project/', 'projects.views.project', name='project'),
url(r'^sched/(?P<project_id>\d+)/$', 'projects.views.schedule'),
url(r'^luminaires/(?P<project_id>\d+)/$', 'projects.views.luminaires'),
url(r'^luminaire/(?P<project_id>\d+)/(?P<luminaire_id>\d+)/$', 'projects.views.luminaire'),
url(r'^deleteproject/(?P<project_id>\d+)/$', 'projects.views.deleteproject', name = 'deleteproject'),
url(r'^admin/', include(admin.site.urls)),
# Examples:
# url(r'^$', 'relume.views.home', name='home'),
# url(r'^relume/', include('relume.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),
)
After looking at your urls.py file, it seems you have a typo in the login's line of urls where you have used project instead of projects.

django reverse() failing

simply put mentions of reverse() anywhere in my project were failing, and so was {% url %}.
I have since made some progress if you scroll to the bottom!
relevant files
root/urls.py
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.views import serve as serveStatic
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^dbrowse/', include('dbrowse.urls')),
(r'^static/', serveStatic),
url(r'^$', 'core.views.viewHallo',name='home'),
)
root/core/views.py
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from site import site_store
def viewHallo (request):
pass
return render_to_response ('core.html',
{'site':site_store,
'title':'i am the hallo view',
'content':'Hallo World!',},
context_instance=RequestContext(request))
Notes
I first noticed the reverse() failing when i had a file called site.py in my project that tried to call reverse(). I was using it to store site settings. I was using the file because
I didn't want to use the bother the database with data that would rarely change.
If I nuked my projects database I didn't want my site settings also going down
I have since found a way to use models to achieve the two goals.
but all that is just extra background info, in case you here someone commenting about a site.py.
update 25/02/11
well here goes!
first notice that urls.py has (r'^dbrowse/', include('dbrowse.urls')). that caused reverse() to fail. I'll explain later...
as for the template tag, I've discovered that the {% url %} doesnt take variables. I took this completely for granted.In fact when I was testing the template tag, i'd just go in and hard code something such as {% url 'home' %} which would work and sometimes i'd test {% url home %} with home being a variable. I din't even see this as being completely different test cases.
But i now know {% load url from future %} allows you to use variables as arguments to {% url %}
Anyway, now back to the (r'^dbrowse/', include('dbrowse.urls')) in urls.py
I had a folder like so
project\
--dbrowse\
__init__.py
urls.py
now this is dbrowse/urls.py
from django.conf.urls.defaults import patterns, url
#databrowse
from django.contrib import databrowse
databrowse.site.register(MyModel)
urlpatterns = patterns('',
url(r'(.*)',databrowse.site.root, name='dbrowse'),)
this was my attempt to avoid having to put databrowse.site.register(MyModel) in my project's root urls.py like the docs suggested. I dont like the idea of polluting my projects main urls.py with databrowse.site.register(MyModel)
however I still dont understand why this caused reverse() to break. but i'm supecting it's to do with (.*) being in the pattern.