How to fix error testing Authentication user? - python

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'),

Related

django-registration registration and activation complete view NoReverseMatch

[Another Update:]
I solved this and posted an answer below but if anyone has a cleaner solution that would be welcome!
[Update]: I've been able to fix the problem with registration_complete by specifying a success_url in a custom MyRegistrationView. But this doesn't work for ActivationView and it's still throwing a NoReverseMatch error while looking for a 'django_registration_activate_complete' pattern. Updated code is below.
I'm trying to implement django-registration for my webapp, and am getting NoReverseMatch errors for both my 'django_registration_activation_complete' and 'django_registration_complete' views.
When I register a new user, instead of redirecting to my 'registration_complete' view after hitting submit, I get the following NoReverseMatch error (below). The email with the activation link sends properly, and when the activation link is clicked, the user is marked as active and can sign in. However, clicking the activation link leads to a similar NoReverseMatch error, and my 'activation_complete' template doesn't show.
I have a custom user model inheriting from AbstractUser, so I had to create my own user registration form, but aside from that I don't think I'm missing anything from the django-registration quickstart guide.
My templates are all in the folder 'C:\Projects\PyDev\group_work\users\templates\django_registration' and are named as described in the quickstart guide
This is my first question so please let me know if anything is unclear or missing.
Traceback (most recent call last):
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django_registration\views.py", line 52, in dispatch
return super().dispatch(*args, **kwargs)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django_registration\views.py", line 96, in form_valid
return HttpResponseRedirect(self.get_success_url(self.register(form)))
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django_registration\views.py", line 93, in get_success_url
return super().get_success_url()
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\views\generic\edit.py", line 51, in get_success_url
if not self.success_url:
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\utils\functional.py", line 119, in __wrapper__
res = func(*self.__args, **self.__kw)
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Projects\PyDev\group_work\gw_env\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'django_registration_complete' not found. 'django_registration_complete' is not a valid view function or pattern name.
urls.py:
urlpatterns = [
path('accounts/register/', RegistrationView.as_view(
form_class=UserRegisterForm),
name = 'django_registration_register',),
path('accounts/activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='django_registration_activate'),
path('accounts/',
include('django_registration.backends.activation.urls')),
]
[Edit] in views.py (the MyActivationView doesn't solve my problem)
class MyRegistrationView(RegistrationView):
success_url = reverse_lazy('users:django_registration_register_complete')
class MyActivationView(ActivationView):
success_url = reverse_lazy('login')
[Another Edit] this is also something I've tried, in urls.py, which didn't work:
path('activate/complete/', TemplateView.as_view(
template_name = 'django_registration/activation_complete.html'
), name='django_registration_activation_complete'),
I solved this by adding the success url path to my main urls.py, instead of the one in my app:
path('activate/complete/', TemplateView.as_view(
template_name='django_registration/activation_complete.html'
), name='django_registration_activation_complete'),

how to fix the following error regarding fetching url

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!

TypeError: __init__() got an unexpected keyword argument 'method'

Well, I am writing a Flask project, but when I tried to python manage.py
The traceback told me that:
Traceback (most recent call last):
File "manage.py", line 5, in <module>
from app import db,create_app
File "/home/humbert/2017-sharing-backend/sharing/app/__init__.py", line 42, in <module>
app.register_blueprint(main_blueprint, url_prefix='/main')
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 951, in register_blueprint
blueprint.register(self, options, first_registration)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 154, in register
deferred(state)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 173, in <lambda>
s.add_url_rule(rule, endpoint, view_func, **options))
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/blueprints.py", line 76, in add_url_rule
view_func, defaults=defaults, **options)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "/home/humbert/venv/local/lib/python2.7/site-packages/flask/app.py", line 1043, in add_url_rule
rule = self.url_rule_class(rule, methods=methods, **options)
TypeError: __init__() got an unexpected keyword argument 'method'
I think my manage.py is right,and I can't figure out the mistake.
The mistake part of __init__.py is that:
from .main import main as main_blueprint
app.register_blueprint(main_blueprint, url_prefix='/main')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix="/auth")
from . import views
I really need some help, thanks!
I had a similar problem. In my code I had a line
#bp.route('/<init:id>/delete', method=('POST'))
The keyword method needs to be changed to methods(with an s)
I had encountered a similar problem in my code and just had to change the keyword "method" to "methods":
#app.route('/login', methods = ['GET', 'POST'])

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.

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