ImportError: cannot import name 'patterns' - django

I have a problem with Django, I created a 'login' app and added the URL on mysite/urls.py as below:
from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
url(r'^user-auth/', include('user_auth.urls')),
url(r'^file-upload/', include('file_uploader.urls')),
url(r'^pagination/', include('pagination.urls')),
patterns('login.views',
url(r'^login/', 'loginView'),
url(r'^greeting/', 'formView'),
url(r'^logout/', 'logoutView')
)
]
However, when I started the server, I received the message on console as:
File "/home/win/Python/mysite/mysite/urls.py", line 16, in <module>
from django.conf.urls import include, patterns, url
ImportError: cannot import name 'patterns'
Do you meet any problem like this? and any resolution do you have to resolve it.
Please please help me.
Thanks

In the latest release of Django (as of this post), patterns is not used.
You can use re_path for the same effect. For Example:
from django.urls import include, re_path
from django.contrib import admin
from myapp.views import *
urlpatterns = [
re_path(r'^admin', include(admin.site.urls)),
re_path(r'^$', home, name='home'),
]
For more information please follow: Documentation

FYI patterns has been removed in Django 1.10. See release 1.10 notes:
https://docs.djangoproject.com/en/2.0/releases/1.10/
If you want to use earlier versions (but i don't see why you would want to do it) , anything below that i.e. 1.9 should be ok, but do note it has been slotted for deprecation since 1.8 i think.
And if you're using django, especially if you are new, I don't see why you would want to use your own login app. Django has a very mature and customizable auth backend. For starters, I strongly suggest you check it out. Useful examples of usage at https://djangobook.com/authentication-views/

If you are using the latest version of Django, then patterns is has been deprecated. You would simply use URL and/or Path depending on if you are on 1.11 or 2.0. If you require patterns, then you would need to downgrade to an earlier Django version.

Related

ImportError: from django.urls import path is not working

What is the probelm ?I am getting lot of stress with this code.
MY CODE::::
from django.contrib import admin
from django.urls import path
from basicapp import views
urlpatterns = [
path('',views.index,name='index'),
path('admin/', admin.site.urls),
path('formpage/',views.form_name_view,name='form_name'),
]
PROBLEM///ERROR::::
from django.urls import path
ImportError: cannot import name path
django.urls.path is new in Django 2.0. Make sure you use Django 2.0 or if you have to stick to <2.0 use django.conf.urls.url.
Docs for path (2.0): https://docs.djangoproject.com/en/2.1/ref/urls/#path
Docs for url (<2.0): https://docs.djangoproject.com/en/1.11/ref/urls/#url
It helps to use an editor that manages imports for you like PyCharm or Visual Code or Vi with appropriate plugins or many other.

In Django 1.11 getting Circular Import Errors When including app URLconf files in project URLconf File

I'm new to Django, have been doing several tutorials to get really comfortable with the structuring, and am now running through the official tutorial.
I've created an polls App, which has a polls/views.py file as follows:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello, World. You're at the polls index.")
I've also created an App URLconf file polls/urls.py with the following code:
from django.conf.urls import url
from . import views
url_patterns = [
url(r'^$', views.index, name='index'),
]
This is pretty much exactly as done in the Django tutorial.
My issue is when I'm specifying url routes in the main projectname/url.py file on a project level as such:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
When doing this, I get the following error:
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'ProjectFolder\\polls\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
This is how the official Django tutorial dictates it to be done. However, if I explicity import the polls/views.py file from the app, I can accomplish the task as follows:
from django.conf.urls import url
from django.contrib import admin
from polls import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', views.index),
]
My immediate concern is the import of every app/urls file I ever create being necessitated by this approach, as well as the obvious divergence from the official Django instruction.
I hesitated to even ask this question because I feel that such a fundamental issue has bound to have an easy fix. Any help would be greatly appreciated.
To clarify, I can get around the error by explicitly importing the view files from apps. Whenever using the Django documentation-described approach of using the include() function I receive the error. I can appreciate the value of this function, and would like to know why is giving me the error described above.
Just writte urlpatterns = [ .. and not url_patterns in your poll.views.py.

ImportError: No module named defaults

I am using django 1.9 version and I wanted to implement ajax search in my application. In the documentation it is says to add the urls to the root url patterns.
url(r'^ajax_search/',include('ajax_search.urls')),`
Then I am getting an import error as follows:
File "/usr/local/lib/python2.7/dist-packages/django_ajax_search-1.5.1-py2.7.egg/ajax_search/urls.py", line 1, in <module>
from django.conf.urls.defaults import *
ImportError: No module named defaults
Can any one help me solve this issue?
django.conf.urls.defaults has been removed from Django 1.6 onwards.
django-ajax-search package was last updated in 2013. The package has not been updated for a long and will not work smoothly for Django 1.9
Either you can find another package or you can manually update it.
django.conf.urls.defaults is deprecated in Django 1.4, later removed in Django 1.6. Read this. And the package you are using has the urls not compatible with Django 1.9. According to the Django 1.9 documentation you should define your urls.py as,
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/([0-9]{4})/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]
UPDATE:
You can modify your urls.py as below to make this working,
from django.conf.urls import url, include
from ajax_search import views as as_views
ajax_search_urlpatterns = [
url(r'^xhr_search$','as_views.xhr_search'),
url(r'^search/', 'as_views.search'),
]
urlpatterns = [
url(r'^ajax_search/',include(ajax_search_urlpatterns)),
]

Redirect to named url pattern directly from urls.py in django?

In Django, how can I do a simple redirect directly from urls.py? Naturally I am a well organized guy, favoring the DRY principle, so I would like to get the target based on it's named url pattern, rather than hard coding the url.
If you are on Django 1.4 or 1.5, you can do this:
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-page/$', RedirectView.as_view(url=reverse_lazy('my_named_pattern'), permanent=False)),
...
If you are on Django 1.6 or above, you can do this:
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-page/$', RedirectView.as_view(pattern_name='my_named_pattern', permanent=False)),
...
In Django 1.9, the default value of permanent has changed from True to False. Because of this, if you don't specify the permanent keyword argument, you may see this warning:
RemovedInDjango19Warning: Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. Set an explicit value to silence this warning.
This works for me.
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-page/$', RedirectView.as_view(url='/')),
...
In above example '/' means it will redirect to index page,
where you can add any url patterns also.
for django v2+
from django.contrib import admin
from django.shortcuts import redirect
from django.urls import path, include
urlpatterns = [
# this example uses named URL 'hola-home' from app named hola
# for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
path('', lambda request: redirect('hola/', permanent=False)),
path('hola/', include("hola.urls")),
path('admin/', admin.site.urls),
]
I was trying to redirect all 404s to the home page and the following worked great:
from django.views.generic import RedirectView
# under urlpatterns, added:
url(r'^.*/$', RedirectView.as_view(url='/home/')),
url(r'^$', RedirectView.as_view(url='/home/')),
This way is supported in older versions of django if you cannot support RedirectView
In view.py
def url_redirect(request):
return HttpResponseRedirect("/new_url/")
In the url.py
url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),
You can make it permanent by using HttpResponsePermanentRedirect
You could do straight on the urls.py just doing something like:
url(r'^story/(?P<pk>\d+)/',
lambda request, pk: HttpResponsePermanentRedirect('/new_story/{pk}'.format(pk=pk)))
Just ensure that you have the new URL ready to receive the redirect!!
Also, pay attention to the kind of redirect, in the example I'm using Permanent Redirect

Django overwrite applications urls

I have a project with three applications installed. The first (photologue) is working fine, but I'm having problems with the last two. My urls.py file in the Django site looks like this:
from django.conf.urls.defaults import patterns, include, url
from django.contrib import auth
from django.contrib import admin
from funvisis.users.models import FVISUser
admin.site.register(FVISUser)
admin.autodiscover()
urlpatterns = patterns(
'',
(r'^admin/', include(admin.site.urls)),
(r'^photologue/', include('photologue.urls')),
(r'^inspeccionespuentes/', include('funvisis.bridgeinspections.urls')),
(r'^inspeccionesedificios/', include('funvisis.buildinginspections.urls')),
)
The urls.py file on both of my applications looks like:
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from .admin import admin_site
from .views import csv_view
urlpatterns = patterns('',
url(r'^csv/(?P<models_url>\w+)/', csv_view),
(r'', include(admin_site.urls),
)
The problem arise when I try to reach the url "^inspeccionesedificios/", since there is no link to add a new buildinginspection and the link to list all the inspections is formed as "http://127.0.0.1:8000/inspeccionespuentes/buildinginspections/" (note how it starts with "inspeccionespuentes" rather than "inspeccionesedificios").
If I change the order of the patterns in the Django site from:
(r'^inspeccionespuentes/', include('funvisis.bridgeinspections.urls')),
(r'^inspeccionesedificios/', include('funvisis.buildinginspections.urls')),
to:
(r'^inspeccionesedificios/', include('funvisis.buildinginspections.urls')),
(r'^inspeccionespuentes/', include('funvisis.bridgeinspections.urls')),
results in the same behaviour but with the problem in "inspeccionespuentes".
I have recently migrated from Django 1.3 to Django 1.4 and this problem ain't appeared before the migration. Any idea?
Thanks!