Django, upgrading to 1.9 - django

I evolve my Django version to 1.9 (before I had the 1.6 or 1.7), so I modify many obseltes things...
But I have a problem with theses lines in my urls.py :
import django
import main_app
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView, ListView
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from main_app.views import *
from main_app.views import password_reset_confirm
... # many urls
url(r'^authentification/$', django.contrib.auth.views.login),
url(r'^forget/send/$', django.contrib.auth.views.password_reset_done),
url(r'^password/$', django.contrib.auth.views.password_reset),
url(r'^password_forget/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', main_app.views.password_reset_confirm),
url(r'^password-init/$', django.contrib.auth.views.password_reset_complete),
I have this error when I write "python manage.py runserver" :
Unhandled exception in thread started by <function wrapper at 0x7f5bcf01af50>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 10, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 19, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/yb/web/carzuip/carzuip/urls.py", line 55, in <module>
url(r'^authentification/$', django.contrib.auth.views.login),
NameError: name 'django' is not defined
I don't understand why I have a problem just with those 5 urls ??!
Thank's

That code doesn't show you importing django: it shows you importing elements underneath it, but never the name itself. It is a fundamental principle of Python that you must import or define every name you use. In your case, import django at the top would work, although note you would then have another problem when the code gets to the password_reset URL since that is referenced from main_app which you again haven't imported.

Try to create a new project with django-admin startproject and copy over the needed settings / copy over manage.py and wsgi.py.
Some releases had breaking changes, i.e. on how the wsgi module imports certain django stuff. Most projects can easy be recreated and you have the newest django defaults in the files.
It's of course just a guess, but worth trying. If you're using a virtualenv, you may need to recreate some things inside, when your python was upgraded / you moved the virtualenv. Such stuff can be quite annoying sometimes.

Resolved !
Euh I think...
Just I add these lines :
from django.contrib.auth.views import login
from django.contrib import auth
And it's works !
It's normal hein ?

Related

Circular Import error in Django occurs only when i import geemap package

I am trying to use geemap in combination with django to build a web app for plotting satellite data. I have installed the geemap package in my django project. My projects name is CustomMaps, and the directory structure is as below.
enter image description here
The code for my CustomMaps.urls.py
is as below
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
urlpatterns = [
path('admin/', admin.site.urls),
path('plotmap/', include('PlotMap.urls')),
]
The code for my PlotMap.urls.py is as follows
from django.urls import path
from django.conf.urls import include, url
from .views import hello
urlpatterns = [
path('hello/', hello, name = 'hello'),
]
And my PlotMap.views.py is as follows
from django.http import HttpResponse
from django.shortcuts import render
import geemap as gm
#import pandas as pd
def hello(request):
map = gm.Map()
return render(request, "PlotMap/hello.html", { "m" : map})
But I am getting the following error on running the project
Exception in thread django-main-thread:
Traceback (most recent call last):
File "D:\Internship\Django App\MyProject\lib\site-packages\django\urls\resolvers.py",
line 604, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "D:\Internship\Django App\MyProject\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\Internship\Django App\MyProject\lib\site-packages\django\urls\resolvers.py",
line 416, in check
for pattern in self.url_patterns:
File "D:\Internship\Django App\MyProject\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Internship\Django App\MyProject\lib\site-packages\django\urls\resolvers.py",
line 611, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'CustomMaps.urls' 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.
But if I run same code after changing my views.py like below it works perfectly fine.
from django.http import HttpResponse
from django.shortcuts import render
#import geemap as gm
#import pandas as pd
def hello(request):
#map = gm.Map()
return render(request, "PlotMap/hello.html", { })
I am not able to understand why is my 'import geemap' leading to circular import error in CustomMaps.urls.py. I tried searching for the same, but have not been able to find anything till now. If someone can please help me out then i will be able to proceed with my work soon, Thank You.
Actually, I tried installing a new version of python(3.8) and also downloaded a new version of geemap(0.11.4) which solved the issue.
But, I am still struggling on how to display the instance of geemap.Map() in my django template, any suggestions would be much helpful.
I will post a new question for the same.
Here: How to display an instance of geemap.Map() in Django Template

cannot import name importlib for rest_framework.urlpatterns

I am learning how to create a Rest API in django. in views.py, adding
from rest_framework.urlpatterns import format_suffix_patterns
is causing
ImportError: cannot import name importlib. I searched that this is because I am using Django 1.9 or more maybe. But can't figure out how to solve this.
Thanks for help.
Tutorial that I am following: https://www.youtube.com/watch?v=QW_5xCCPWFk&index=40&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK
full traceback
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7f1b5badc500>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 10, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 19, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sonali/Videos/rest_api_project/rest_api_project/urls.py", line 20, in <module>
from rest_framework.urlpatterns import format_suffix_patterns
File "/usr/local/lib/python2.7/dist-packages/rest_framework/urlpatterns.py", line 4, in <module>
from rest_framework.settings import api_settings
File "/usr/local/lib/python2.7/dist-packages/rest_framework/settings.py", line 23, in <module>
from django.utils import importlib
ImportError: cannot import name importlib
Python version 2.7.6
The django.utils.importlib module was removed in Django 1.9. It looks as if you are running an old version of rest framework that does not support Django 1.9.
Support for Django 1.9 was added in rest framework 3.3, and the current version is 3.6.3.
If your tutorial was written for Django 1.8, then you might find it easier to complete the tutorial using Django 1.8. If it was written for an earlier version of Django that that, then it would probably be better to look for a new tutorial.

cannot import LoginView?

i'm learning some things about Django 1.9 and i want to make a login form but with class-based views.
This is mi view code:
from django.shortcuts import render
from django.contrib.auth.views import LoginView
class AlumnoLoginView(LoginView):
template_name = "alumno/login.html"
redirect_authenticated_user = True
And this is my urls code:
from django.conf.urls import url, include
from .views import AlumnoLoginView
app_name = 'alumno'
urlpatterns = [
url(r'^login/$', AlumnoLoginView.as_view(), name="login"),
]
This make an error:
ImportError: cannot import name LoginView
But if I delete the code inside urls nothing happens.
This is the full error trace (with François change):
Unhandled exception in thread started by <function wrapper at 0x7f044ad8ac08>
Traceback (most recent call last):
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/studentadmin/urls.py", line 21, in <module>
url(r'^alumno/', include('alumno.urls')),
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/urls.py", line 3, in <module>
from alumno.views import AlumnoLoginView
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/views.py", line 3, in <module>
from django.contrib.auth.views import LoginView as BaseLoginView
ImportError: cannot import name LoginView
What is wrong?
How I fix it?
Thank :)
Class-based views LoginView and LogoutView are introduced on Django 1.11 and function-based views 'login' and 'logout' are deprecated since then.
You can use class-based views LoginView and LogoutView like this:
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
url(r'^login/$', LoginView.as_view(template_name='...'), name="login"),
]
There's no view called LoginView in django.contrib.auth.views
I think you need.
from django.contrib.auth.views import login
LoginView only available from Django 1.11
cannot import LoginView?
You must be using lower version of django ..Login view supported only in 1.11 or higher version..
You need to install 1.11 or higher version
pip install django==1.11

AppRegistryNotReady: lazy format_html()?

Why do I get this exception?
Traceback (most recent call last):
File "/path1/myapp-isu/myapp_isu/tests/unit/views/test_view_isu.py", line 8, in <module>
from myapp_isu.search_form import ISUSearchForm
File "/path1/myapp-isu/myapp_isu/search_form.py", line 87, in <module>
class ISUSearchForm(forms.Form):
File "/path1/myapp-isu/myapp_isu/search_form.py", line 108, in ISUSearchForm
foo_filter=forms.ModelChoiceField(FooFilter.objects.all(), label=format_html('%s', reverse_lazy('foo-filter'), FooFilter._meta.verbose_name))
File "/path1/dt/dt/utils/templateutils.py", line 127, in reverse
return urlresolvers.reverse(*args, **kwargs)
File "/path1/dt/dt/utils/urlresolverutils.py", line 49, in patched_reverse
base_url = orig_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, prefix=prefix, current_app=current_app)
File "/path2/django/core/urlresolvers.py", line 578, in reverse
return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/path2/django/core/urlresolvers.py", line 432, in _reverse_with_prefix
self._populate()
File "/path2/django/core/urlresolvers.py", line 284, in _populate
for pattern in reversed(self.url_patterns):
File "/path2/django/core/urlresolvers.py", line 401, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/path2/django/core/urlresolvers.py", line 395, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/path1/myapp-eins/myapp_eins/etc/rooturls.py", line 13, in <module>
admin.autodiscover()
File "/path2/django/contrib/admin/__init__.py", line 24, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/path2/django/utils/module_loading.py", line 67, in autodiscover_modules
for app_config in apps.get_app_configs():
File "/path2/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/path2/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
It only happens if I call the unittest via PyCharm, not if I use py.test on the shell.
I guess reverse_lazy() is not lazy here, since it gets used in format_html(). Any way to have a lazy format_html()?
Versions:
Django 1.8
Pycharm 5.0.4
Since there are things like url_patterns in the stacktrace, I assume that DJANGO_SETTINGS_MODULE is set correctly .
But, you still need to call django.setup() before running anything else.
import django
django.setup()
For me, that made this error message go away.
I've had some trouble using PyCharm, myself, and I'll assume you're using the the community edition (which I've been using).
If so, the problem is very likely that you're not properly configured for django. You can probably fix this with some hacks that might work for this.
I'd start off with this.
(importing django to ensure the django console is run)
Then maybe this.
There's also this:
Check "Edit Configurations" under the test you're running, and add DJANGO_SETTINGS_MODULE=<app-name-here>.settings to environment variables.
If all of the above fails, try initializing your form and doing the import in the constructor:
class ISUSearchForm(...):
...
foo_filter = forms.Field()
...
def __init__(*args, **kwargs)
from ... import reverse_lazy
from ... import FooFilter
self.fields['foo_filter'] = \
forms.ModelChoiceField(
FooFilter.objects.all(),
label=format_html(
'%s',
reverse_lazy('foo-filter'),
FooFilter._meta.verbose_name
)
)
super().__init__(*args, **kwargs)
The error may be caused by the exact import sequence performed by the different test runners and the fact that you use only class variables to customize your form.
In django 1.8, reverse() and reverse_lazy() now return Unicode strings instead of byte strings.
Please refer the link:
https://docs.djangoproject.com/en/1.8/releases/1.8/

./manage.py test of Django 1.4 gives a Thing2Literal import not found on google appengine

I followed the steps here https://developers.google.com/cloud-sql/docs/django and it ran well with django 1.3.1. Now up to Django 1.4 and gives a funny stack trace. I would paste the relevant part of the message here
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 69, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/home/dumb906/woody/py/mdlr/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/dumb906/woody/py/mdlr/django/core/management/commands/test.py", line 7, in <module>
from django.test.utils import get_runner
File "/home/dumb906/woody/py/mdlr/django/test/__init__.py", line 5, in <module>
from django.test.client import Client, RequestFactory
File "/home/dumb906/woody/py/mdlr/django/test/client.py", line 21, in <module>
from django.test import signals
File "/home/dumb906/woody/py/mdlr/django/test/signals.py", line 2, in <module>
from django.db import connections
File "/home/dumb906/woody/py/mdlr/django/db/__init__.py", line 40, in <module>
backend = load_backend(connection.settings_dict['ENGINE'])
File "/home/dumb906/woody/py/mdlr/django/db/__init__.py", line 34, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/home/dumb906/woody/py/mdlr/django/db/utils.py", line 92, in __getitem__
backend = load_backend(db['ENGINE'])
File "/home/dumb906/woody/py/mdlr/django/db/utils.py", line 44, in load_backend
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: 'google.appengine.ext.django.backends.rdbms' isn't an available database backend.
Try using django.db.backends.XXX, where XXX is one of:
'dummy', 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3'
Error was: cannot import name Thing2Literal
Any help? Some one said it needs to be compiled http://django-irc-logs.com/2012/mar/27/ ?
I had the same issue. Since the problem is with importing Thing2Literal that is used by adapt_datetime_with_timezone_support function from django/db/backends/mysql/base.py and according to this:
https://code.djangoproject.com/changeset/17596/django/trunk/django/db/backends/mysql/base.py this is important only to datetime objects that bypass the model layer and are used with raw sql. So i decided it is not important for me and I messed a bit my django/db/backends/mysql/base.py: comment out code that causes trouble (import of Thing2Literal, adapt_datetime_with_timezone_support function and line 83 where the function is called)
Of course I upload my django 1.4 customized that way to appengine together with my project and it works.
I would appreciate feedback from those who understand django internals better, whether what i've done is ok assuming i don't use raw sql at all.
As you can see in the documentation you've linked, Google App Engine support only Django up to version 1.3 (actually 1.3.1).