how to fix the following error regarding fetching url - python

I am not able to access (fetch) those urls mentioned in program
urls.py
from django.conf.urls import include, url
from rest_framework import routers
from imgstore.views import QueryImage
from imgstore.views import ImageActionViewSet
# this is DRF router for REST API viewsets
router = routers.DefaultRouter()
router.register(r'api/v1/imgaction', ImageActionViewSet, r"imgaction")
router.register(r'api/v1/queryimage', QueryImage, r"queryimage")
urlpatterns = [
url(r'', include(router.urls, namespace='imgaction')),
url(r'', include(router.urls, namespace='queryimage'))
]
I receive this error:
Error occured while running server:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns iter(patterns)TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 914, in _bootstrap_innerself.run()
File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 862, in runself._target(*self._args, **self._kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapperfn(*args, **kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_runself.check(display_num_errors=True)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks,
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checksreturn checks.run_checks(**kwargs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checksnew_errors = check(app_configs=app_configs)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolverreturn check_method()
File"/root/.pyenv/versions/3.5.7/lib/python3.5/sitepackages/django/urls/resolvers.py", line 398, in checkfor pattern in self.url_patterns:
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__res = instance.__dict__[self.name] = self.func(instance)
File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'image_storage.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.
And I have no idea about to solve it. What am I missing?

Check the file urls.py that may exist in image_storage django app. It should contain a valid django url configuration and not be empty!

So often times this is caused by some exception when Django's resolvers.py tries to consume your urls.py.
The way I generally solve it is to wrap my entire urls.py file (along with all other urls.py files) in a try-except block, and print the exception that gets caught, which is often much more immediately useful to solving the problem than the default one Django provides.
Good luck!

Related

How to fix error testing Authentication user?

I'm learning Drf, I'm figuring out to Athuenticate user login Testapi in Drf, it showing error Not valid view function or pattern name. Can Anyone suggest what is wrong with the code?
URLS.PY
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('college.urls')),
path('auth',include('rest_framework.urls'), name='rest_framework'),
]
TEST.PY
USER_URL = reverse('auth')
class StudentsDetailsTestCase(APITestCase):
def test_login_user(self):
self.assertTrue(self.client.login(username='***',
password='***'))
response = self.client.get(USER_URL)
self.assertEqual(response.status_code,status.HTTP_200_OK)
traceback error
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name
__import__(name)
File "C:\Users\collegedjango\MYSITE\college\tests.py", line 35, in <module>
USER_URL = reverse('auth')
File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 47, in reverse
url = _reverse(viewname, args, kwargs, request, format, **extra)
File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 60, in _reverse
url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\resolvers.py", line 729, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'auth' not found. 'auth' is not a valid view function or pattern name.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
you need to use it with rest_framework because of this line path('auth',include('rest_framework.urls'), name='rest_framework'),
you can update reverse by reverse(rest_framework) or you can change line to path('auth',include('rest_framework.urls'), name='auth'),

Trying to find the circular reference in my django urlpatterns using django-subdomains?

I'm getting a the url conf correct for my web app, and I'm at a loose end.
I think the idea behind django-subdomains is that the subdomain routing is stored in the SUBDOMAIN_URLCONFS
ROOT_URLCONF = 'creativeflow'
# A dictionary of urlconf module paths, keyed by their subdomain.
SUBDOMAIN_URLCONFS = {
None: ROOT_URLCONF + '.urls', # no subdomain, e.g. ``example.com``
'www': ROOT_URLCONF + '.urls',
'blog': 'blog.urls',
}
Then my creativeflow.urls and blog.urls are:
"""Creativeflow URL Configuration."""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls, name="admin"),
]
And
"""Creativeflow URL Configuration the blog app."""
from django.conf.urls import url
from .views import BlogListView
urlpatterns = [
url(r'posts/^(?P<year>\d{4})/(?P<months>\d{2}|\w{3})/(?P<day>\d{2})',
BlogListView.as_view(paginate_by=25), name="blog-list-view")
]
The error I'm seeing is:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x046FA618>
Traceback (most recent call last):
File "D:\creativeflow\myvenv\lib\site-packages\django\core\urlresolvers.py", line 419, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\creativeflow\myvenv\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "D:\creativeflow\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "D:\creativeflow\myvenv\lib\site-packages\django\core\management\base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "D:\creativeflow\myvenv\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\creativeflow\myvenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\creativeflow\myvenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "D:\creativeflow\myvenv\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\creativeflow\myvenv\lib\site-packages\django\core\urlresolvers.py", line 426, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'creativeflow' 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.
I'm assuming that, as you can see, I have an urlpatterns in both urls.py. So I must have a circular reference. But I've followed the imports from through views.py and models.py and I don't see anything that would cause a circular dependency problem.
How do I resolve this/and find the circular dependency?
Your ROOT_URLCONF points to a module without any patterns. The ROOT_URLCONFmodule must at least have a urlpatterns attribute, even if it's an empty list. You probably want this to point to creativeflow.urls.

when i run my django project on terminal i get the AttributeError: 'str' object has no attribute 'regex'

When i run my Django app on terminal i get the following error:
Unhandled exception in thread started by <function wrapper at 0x7f51ce501aa0>
Traceback (most recent call last):
File "/home/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/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/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/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/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 31, in check_resolver
warnings.extend(check_pattern_startswith_slash(pattern))
File "/home/macrewsupreet/heroku_wheredego1/wheredg-backend/macrewsupreet/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 67, in check_pattern_startswith_slash
regex_pattern = pattern.regex.pattern
AttributeError: 'str' object has no attribute 'regex'
My main urls.py file
urlpatterns =[
url(r'^api/account/', include("wheredego_service.accounts.account_urls")),
url(r'^api/fileupload/', include("wheredego_service.file_manager.file_manager_urls")),
url(r'^api/activity_category', include(
"wheredego_service.activity_category.activity_category_urls")),
url(r'^api/destination', include("wheredego_service.destinations.destination_urls")),
url(r'^api/trip', include("wheredego_service.trip.trip_urls")),
url(r'^api/bucket', include("wheredego_service.bucket.bucket_urls")),
url(r'^api/experience', include("wheredego_service.experience.experience_urls")),
url(r'^api/region', include("wheredego_service.region.region_urls")),
url(r'^api/friend', include("wheredego_service.friend.friend_urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is My Trip app's views and i have followed the same pattern in all url files.
from django.conf.urls import url
from wheredego_service.trip import trip_views
from wheredego_service.trip.itinerary import itinerary_views
urlpatterns =[
url(r'^/(?P<trip_id>[0-9,a-z,_]+)/itinerary', itinerary_views.ListItineraryTripView.as_view()), url(r'^/me', trip_views.ListMyTripsView.as_view()), ]
Please help how to resolve this error.
In one of your urls.py files, you have a string in the list of URL patterns. This could be because you forgot to remove the prefix when you switched from patterns(prefix, ...) to a list of url()s.
You need to look through your urls.py and find something like:
urlpatterns =[
'' # <- this is the problem, remove this string
url(...)
url(...)
]
Unfortunately, it's not possible for us to tell which urls.py the problem is in. You could try commenting out the includes() one by one. If the error stops, then you've found the one that's causing the problem.
In Django 1.10, the url checks have improved slightly, the check_pattern_startswith_slash won't fail any more, and you'll get a specific warning about the string instead.

How to Integrate Pyramid 1.1 and Mongo DB - as few lines as possible

Goal: I try to integrate Mongo DB with Pyramid 1.1 basic application.
Background: Appliation is created by the book (https://docs.pylonsproject.org/projects/pyramid/1.1/narr/project.html#creating-the-project) using basic command "paste create -t pyramid_starter"
I followed this cookbook article: https://docs.pylonsproject.org/projects/pyramid_cookbook/dev/mongo.html
Problem: It seems that when ever I add MongoDB connection into request I got "Internal Server Error" with
I have tried several articles and it seems that I must start debug system more?
Has anybody found easy solution for this?
Exception if it helps some expert
Exception happened during processing of request from ('127.0.0.1', 53697)
Traceback (most recent call last):
File "virtualenv\lib\site-packages\paste-1.7.5.1-py2.7.egg\paste\httpserver.py", line 1068, in process_request_in_thread
self.finish_request(request, client_address)
File "C:\Python27\Lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\Lib\SocketServer.py", line 639, in __init__
self.handle()
File "virtualenv\lib\site-packages\paste-1.7.5.1-py2.7.egg\paste\httpserver.py", line 442, in handle
BaseHTTPRequestHandler.handle(self)
File "C:\Python27\Lib\BaseHTTPServer.py", line 343, in handle
self.handle_one_request()
...
File "C:\Python27\lib\site-packages\pyramid_debugtoolbar-0.8-py2.7.egg\pyramid_debugtoolbar\panels\__init__.py", line 24, in render
return render(template_name, vars, request=request)
File "virtualenv\lib\site-packages\pyramid-1.2a1-py2.7.egg\pyramid\renderers.py", line 69, in render
return helper.render(value, None, request=request)
File "virtualenv\lib\site-packages\pyramid-1.2a1-py2.7.egg\pyramid\renderers.py", line 418, in render
result = renderer(value, system_values)
File "C:\Python27\lib\site-packages\pyramid_jinja2-1.1-py2.7.egg\pyramid_jinja2\__init__.py", line 277, in __call__
return self.template.render(system)
File "C:\Python27\lib\site-packages\jinja2-2.6-py2.7.egg\jinja2\environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Python27\lib\site-packages\pyramid_debugtoolbar-0.8-py2.7.egg\pyramid_debugtoolbar\panels\templates\request_vars.jinja2", line 110, in top-level template code
<td>{{ value|escape }}</td>
File "virtualenv\lib\site-packages\markupsafe-0.15-py2.7.egg\markupsafe\_native.py", line 20, in escape
return s.__html__()
File "virtualenv\lib\site-packages\pymongo-2.0.1-py2.7-win-amd64.egg\pymongo\collection.py", line 1156, in __call__
self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the '__html__' method on a 'Database' object it is failing because no such method exists.
Another possible solution is to use the 'debugtoolbar.panels' setting in your config file to disable the request_vars panel (which is what is causing the issue):
[app:main]
.. other stuff ...
debugtoolbar.panels =
pyramid_debugtoolbar.panels.versions.VersionDebugPanel
pyramid_debugtoolbar.panels.settings.SettingsDebugPanel
pyramid_debugtoolbar.panels.headers.HeaderDebugPanel
# pyramid_debugtoolbar.panels.request_vars.RequestVarsDebugPanel
pyramid_debugtoolbar.panels.renderings.RenderingsDebugPanel
pyramid_debugtoolbar.panels.logger.LoggingPanel
pyramid_debugtoolbar.panels.performance.PerformanceDebugPanel
pyramid_debugtoolbar.panels.routes.RoutesDebugPanel
pyramid_debugtoolbar.panels.sqla.SQLADebugPanel
Pymongo's Database and Collection objects respond to __getattr__ in order to provide a nicer interface and let you write code like:
db.foo.bar.find(...)
Any call to __getattr__ will succeed, but unfortunately this confuses some libraries which expect certain attributes to be callable (the Pymongo Collection object is not callable, except to raise that exception you're seeing above).
What I've done in Pyramid projects is only use the database from within the resources, to prevent references to the database or collections from becoming present in the module level in views or other code. As an added benefit, this ends up being a good way of enforcing separation of concerns so that resources handle database manipulation, and views only translate that for display in the templates.
That error means that your trying to call a method (html) that doesn't exist in the Database instance.
>>> conn = Connection()
>>> db = conn.mydb
>>> col = db.mycoll
>>> col = db.mycoll()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/virtualenvs/myenv/lib/python2.7/site-packages/pymongo-2.0-py2.7-macosx-10.6-x86_64.egg/pymongo/collection.py", line 1156, in __call__
self.__name)
TypeError: 'Collection' object is not callable. If you meant to call the 'mycoll' method on a 'Database' object it is failing because no such method exists.
If you haven't modified the code then it is possible it's an bug in markupsafe that tries to call html() in a Database instance
s.__html__()

TypeError: 'tuple' object is not callable

I was doing the tutorial from the book teach yourself django in 24 hours and in part1 hour 4 i got stuck on this error.
Traceback (most recent call last):
File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 278, in run
self.result = application(self.environ, self.start_response)
File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 635, in __call__
return self.application(environ, start_response)
File "C:\Python25\lib\site-packages\django\core\handlers\wsgi.py", line 239, in __call__
response = self.get_response(request)
File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 67, in get_response
response = middleware_method(request)
File "C:\Python25\Lib\site-packages\django\middleware\common.py", line 56, in process_request
if (not _is_valid_path(request.path_info) and
File "C:\Python25\Lib\site-packages\django\middleware\common.py", line 142, in _is_valid_path
urlresolvers.resolve(path)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 254, in resolve
return get_resolver(urlconf).resolve(path)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 181, in resolve
for pattern in self.url_patterns:
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 205, in _get_url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py", line 200, in _get_urlconf_module
self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
File "c:\projects\iFriends\..\iFriends\urls.py", line 17, in <module>
(r'^admin/', include('django.contribute.admin.urls'))
TypeError: 'tuple' object is not callable
Can someone help me please..
url.py
from django.conf.urls.defaults import *
####Uncomment the next two lines to enable the admin:
#### from django.contrib import admin
#### admin.autodiscover()
urlpatterns = patterns('',
(r'^People/$', 'iFriends.People.views.index') ,
(r'^admin/', include('django.contrib.admin.urls')),
# Example:
# (r'^iFriends/', include('iFriends.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
)
You somehow set some function to a tuple. Please edit the question and paste your urls.py code, so we can point you to the error.
I can try a wild guess:
File "c:\projects\iFriends\..\iFriends\urls.py", line 17, in <module>
(r'^admin/', include('django.contribute.admin.urls'))
This somehow tells me that you missed a comma on line 16, so:
16. (r'^/', 'some_stuff....') # <-- missed comma here
17. (r'^admin/', include('django.contribute.admin.urls'))
Just put the comma and it will work. If that's not the case, I'll send my cristal ball for mainantance. Paste the code.
EDIT
Seems like you have pasted the urls.py as an answer. Please edit the question and paste urls.py there.
Anyway, the error has changed. What did you do? In this new error, urls.py is not found anymore so maybe you've renamed it? Have you changed the way you run the application?
The file you pasted is not the one that is running. Are you pasting url.py and django is reading urls.py? The code in the error doesn't match the code you pasted! Please paste the correct file, i.e. the same that gives the error, or we can't help.

Categories