Rewrite URL to exclude Django application name - django

on my live server, I am trying to remove/rewrite the need to include the application name in the URL, as without it I get a 404. For example:
http://www.example.com/myapp/page.html
to
http://www.example.com/page.html
This is especially tricky since i don't want this to affect the django admin URL which excludes the app name.
This is on Apache Server on Ubuntu on a shared host (A2).

You're root urls.py most likely looks something like this:
"""
Definition of urls for api.
"""
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^myapp/', include('myapp.urls'))
]
When you just replace r'^myapp/' with r'^' the app will be automatically tried, when there is nothing else before that fits (so it's best to put it to the end of the list)

Related

Why does this URL work in Django? It is not in urls.py

I've never worked with Django before. I'm taking over a Django project that was started by another programmer, who is now long gone. There is some magic happening in the code that I do not understand. For instance, in this file:
urls.py
I see this:
from django.conf.urls import url, include
from django.contrib import admin
from django.core.urlresolvers import reverse_lazy
from django.views.generic.base import RedirectView
from django.conf import settings
from core import views as core_views
from sugarlab.search.views import validate_collections, create_document, delete_interest, rename_interest, add_url, my_interests
from sugarlab.search.views import content, score, terms
from django.contrib.auth.views import logout as django_logout
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
url(r'^admin/logout/$', django_logout,
{'next_page': '/'}),
url(r'^admin/', admin.site.urls),
url(r'^accounts/logout/$', django_logout,
{'next_page': '/'}),
url(r'^accounts/', include('allauth.urls')),
url(r'^unsecured/$', core_views.home),
The confusing part is these two lines:
from django.conf import settings
url(r'^accounts/', include('allauth.urls')),
"allauths" is some configuration set inside of this file:
settings/common.py
The data looks like this:
'allauth',
'allauth.account',
'allauth.socialaccount',
'django.contrib.auth',
'django.contrib.sites',
# Social/3rd party Authentication apps
'allauth.socialaccount.providers.linkedin_oauth2',
'captcha'
Somehow this is a URL that actually works:
/accounts/signup/
This file is completely blank:
settings/__init__.py
So I've two questions:
how does "import settings" manage to magically import allauths?
how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, that would make me think that /accounts/signup/ is a valid url.
how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, that would make me think that /accounts/signup/ is a valid url.
url(r'^accounts/', include('allauth.urls')),
there is another urls file inside the app called allauth if it's installed by "pip" you can find it in the following directory "lib/python*/site-package/allauth"
= the python version you are using for example 2.7 or 3.5
ps allauth is a well known 3rd party app you can quick google search django allauth and you'll find it
how does "import settings" manage to magically import allauths?
it doesnt import settings is used for something else for example setting static file url like that
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

URL Conf - Serving views at the root URL and non root URLs within one app

I've run into a problem configuring the url.py files in a new project. I have one app, which contains two views. The first view should appear at myurl.com, while the other should appear at myurl.com/foo. myurl.com appears without trouble but myurl.com/foo shows a 404 page not found error.
The url.py at the project level looks like this:
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'^$', include('myapp.urls', namespace="myapp")),
)
And the url.py at the app level looks like this:
from django.conf.urls import patterns, include, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.book_search, name='book_search'),
url(r'^foo/', views.myapp, name='myapp')
)
I understand that that django is taking the URL that is submitted and checks it against the url patterns defined at the project level, but I don't know how to direct it to myapp without hosting all of myapp at some url that is not at the root, i.e. myapp.com/bar and myapp.com/bar/foo.
url(r'^$', include('myapp.urls', namespace="myapp")),
Remove the ^$ here. This would force all included URLs to match only if starting with "the end", i.e. nothing.

Page not found 404 on Django site?

I'm following the tutorial on Django's site to create a simple poll app. However, Django is unable to resolve "//127.0.0.1:8000/polls" , even though I've defined the regex in mySite/urls.py. I'm doing this in a virtualenv, with the latest Django (1.7) installed.
mySite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
mySite/polls/urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
mySite/polls/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
mySite/settings.py:
...
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
....
ROOT_URLCONF = 'mySite.urls'
The error I'm getting:
Using the URLconf defined in mySite.urls, Django tried these URL patterns, in this order: ^admin/
The current URL, polls, didn't match any of these.
I had the same problem.
It turns out I was confused because of the multiple directories named "mysite".
I wrongly created a urls.py file in the root "mysite" directory (which contains "manage.py"), then pasted in the code from the website.
To correct it I deleted this file, went into the mysite/mysite directory (which contains "settings.py"), modified the existing "urls.py" file, and replaced the code with the tutorial code.
In a nutshell, make sure your urls.py file is in the right directory.
Django unable to resolve 127.0.0.1:8000/polls because url config defined as r'^polls/'.
Usual workaround:
mySite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
Note:
Whenever Django encounters include(), It chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
mySite/polls/urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('polls.views',
url(r'^$', 'index', name='index'),
)
Note: Instead of typing that out for each entry in urlpatterns, you can use the first argument to the patterns() function to specify a prefix to apply to each view function.
Answer If
If you want to access 127.0.0.1:8000/polls Note: without trailing slash
use view based url
url(r'^polls', 'polls.views.index', name='index'),
So now you can access 127.0.0.1:8000/polls without trailing slash.
You're accessing to http://yourdomain.com/, and you don't have any URL defined for "/".
You have two options:
If you want to access to the index page of your polls application you have to enter the URL: yourdomain.com/polls
You can also modify you mySite/urls.py file to access from just yourdomain.com
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include('polls.urls')),
)
To make the answer clear for beginners who has this issue by following the tutorial, the project root URLconf is the one in the same folder as settings.py which is:
mysite/mysite/urls.py
Just make sure import 'include'. The code looks like:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
So in
mysite/mysite/settings.py:
The line should be:
ROOT_URLCONF = 'mysite.urls'
You don't need create a fresh new root URLconf.
Depending on where you put your ROOT urls.py, you set your ROOT_URLCONFIG accordingly, if you have it in your outermost folder containing manage.py then "urls" is ok. if you have it in someother folder then you have to do ".urls"
Credit for the answer to jerryh91
For more info about how it works, check How Django processes a request
You put the urls.py folder into the outer MySite folder, you are suppose to put it in the inner one so its not mySite/urls.py, but mySite/mySite/urls.py:
ran into the same mistake when i did the tutorial
Another way to access 127.0.0.1:8000/polls would be to redirect the browser when accessing 127.0.0.1:8000. It is done by editing .../mysite/mysite/urls.py as follows:
from django.conf.urls import include, url
from django.contrib import admin
from polls import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^$', views.index, name='index'),
]
Page not found?
If you get an error page here, check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/.
Source : https://docs.djangoproject.com/en/3.0/intro/tutorial01/
Actually the problem is that you didn't notice that
mysite/urls.py and polls/urls.py are two different files and you modified polls/urls.py instead of putting mysite/urls.py in the urls.py file in ...mysite\mysite folder.
In my case, it was a stupid mistake. I wanted to integrate the plugin django-tinymce, and test it. So following this guide, I did the step 3 and exported the variable to the path. As the server runned again, I received the not found error, showing the message:
Using the URLconf defined in testtinymce.urls, Django tried these URL
patterns, in this order: ....
But I didn't know what exactly it was, until I remembered exporting the variable DJANGO_SETTINGS_MODULE
running unset DJANGO_SETTINGS_MODULE in terminal solved my issue. Hope that it helps someone too.
Add the below line in your Mysite/urls.py
url(r'^$', views.index, name='index'),
and check. If you have created your project correctly, it should work. Else something like above might have happened to have more than one files so confused.
2017-10-05_12:03 ~/mysite/mysite
$ vi urls.py
2017-10-05_12:04 ~/mysite/mysite
$ cd ../..
2017-10-05_12:04 ~
$ mv mysite SENSIBLE_NAME_DJANGO_ROOT
i had the same issue and got it resolved by adding /polls after http://server:port/ and so final address in server looks like:
http://server:port/polls

Moving to production environment broke my application

I've just deployed my application on dreamhost and it's stopped working when uploading files. Passenger just produces a 500 internal error. It works on my development set up.
My passenger file looks like:
import sys, os
sys.path.append(os.getcwd())
sys.path.append(os.path.join(os.getcwd(), '/photosoc'))
os.environ['DJANGO_SETTINGS_MODULE'] = "photosoc.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I get the standard 404 error(debug is still enabled). I have had to change my urls file though from:
from django.conf.urls.defaults import patterns, include, url
from competition.models import Image
from competition import *
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
admin.site.register(Image)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'photosoc.views.home', name='home'),
# url(r'^photosoc/', include('photosoc.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^image/$', 'competition.views.index'),
url(r'^image/uploadImage', 'competition.views.uploadImage'),
url(r'^image/uploadCompleted', 'competition.views.uploadCompleted'),
url(r'^image/uploadFailed', 'competition.views.uploadFailed'),
)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
To the following:
from django.conf.urls.defaults import patterns, include, url
from competition.models import Image
from competition import *
from django.contrib import admin
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
admin.site.register(Image)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'photosoc.views.home', name='home'),
# url(r'^photosoc/', include('photosoc.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^image/$', 'competition.views.index'),
url(r'^image/uploadImage', 'competition.views.uploadImage'),
url(r'^image/uploadCompleted', 'competition.views.uploadCompleted'),
url(r'^image/uploadFailed', 'competition.views.uploadFailed'),
)
This is the only change I've made to the application from the switch from development to production. So what else could have gone wrong?
You may have a permission problem.
It seems like you are writing image files. Does the process that is running Django have permission to write files? When you are running Django locally with ./manage.py runserver Django will get the permissions of the user that runs from the command line, but in a typical production environment you'd be running with the permissions of the Apache user. This user may not have permission to write those image files. You could try temporarily hardcoding the write directory to /tmp to see if that makes a difference.
Of course, you will really need see that 500 error stack trace to know what's going on.
Are your settings exactly the same in what middleware classes your importing? Double check that these are the same.
Related:
ModSecurity: Output filter: Failed to read bucket (rc 104): Connection reset by peer

Why an extra slash is getting added to urls?

I've created a blog using django and hosted it on dotcloud http://www.honeybunny.dotcloud.com/blog/ its working fine on the localhost but when i try to access it online an extra slash is added to the urls what could be the reason ?
www.sitename.com/admin/
becomes
www.sitename.com//admin/
my urls.py is as following
from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import redirect_to
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
import blog
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',redirect_to,{'url':'/blog'}),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/',include('blog.urls')),
)
Also submitting the login form on the admin redirects me to http://admin/ while in the local environment it works perfectly fine .
UPDATE : My problem seems remarkably similar to the one described here .
From django tutorials the url file should look like the one below.
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import redirect_to
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'honeybunny.views.home', name='home'),
# url(r'^honeybunny/', include('honeybunny.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^$',redirect_to,{'url':'/blog'}),
url(r'^admin/$', include(admin.site.urls)),
)
Is my urls.py file
I have deleted import blog line because I don't have blog module.
It seemed to be a problem with dotcloud the same code worked without any errors when i uploaded it to epio