I'm using the django-rest-passwordreset package to implement password reset endpoints.
When a given email doesn't exist, it throws a ValidationError exception, causing a 500 error. How can I catch this error, and return a 400 instead? I simply added the urls as shown below, so I don't think I can surround it with an try: except or something similar.
urlpatterns=[
...
url(r'^password/recover/', include('django_rest_passwordreset.urls')),
...
]
Exception:
ValidationError at /password/recover/
{'email': ['There is no active user associated with this e-mail address or the password can not be changed']}
Request Method: POST
Request URL: http://192.168.99.100:8000/password/recover/
Django Version: 2.0.6
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django_rest_passwordreset/views.py" in post
116. code='invalid')}
Exception Type: ValidationError at /password/recover/
Exception Value: {'email': ['There is no active user associated with this e-mail address or the password can not be changed']}
Request information:
USER: AnonymousUser
GET: No GET data
POST: No POST data
FILES: No FILES data
COOKIES: No cookie data
HEADERS: "email" : "bob#thebuilder.com"
I managed to solve it by creating a custom Exception handler as described here.
Additional information:
- Filter on the specific error message to avoid catching ALL ValidationErrors,
- Otherwise return the standard Django exception response.
Related
I'm trying to retrieve a model instance in Django Rest Framework 3.6.3 at /path/to/API/widget/1/, 1 being the primary key of the widget. It's giving me:
retrieve() got an unexpected keyword argument 'pk'
From the trace I think I'm doing something to cause dispatch to throw an exception when instantiating the handler (from views.py, source here). I don't understand what I'm doing wrong through when I examine the source. Here's the trace:
Traceback:
File "/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/viewsets.py" in view
86. return self.dispatch(request, *args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
Exception Type: TypeError at /path/to/API/widget/1/
Exception Value: retrieve() got an unexpected keyword argument 'pk'
Here's the view from the ViewSet:
def retrieve(self, request, some_lookup_field=None):
instance = self.get_object(pk) # handle multi-tenant access control
if not instance:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = self.get_serializer(instance) # from the class's `serializer_cass` attribute
return Response(serializer.data)
As you see in your stacktrace, the error is:
retrieve() got an unexpected keyword argument 'pk'.
Look closely in your retrieve() function:
def retrieve(self, request, some_lookup_field=None):
# ____________________________^
instance = self.get_object(pk) # handle multi-tenant access control
# _________________________^
...
You are taking some_lookup_field as a parameter and not pk, that you use below in self.get_object(pk). Try to rename some_lookup_field to pk.
This error might because you put wrong urls in your url.py. I've had the same problem in my project
I want to access ElasticSearch securely via a Django URL. From this request, I will lookup the user's token to get their primary key. Then I will only show ES results that match.
For now, I just want to connect to my ElasticSearch URL. It would kind of work like a "proxy".
Anyway, the following returns the bottom traceback. How do I set it up correctly? Do I need a serialiser
views.py
from django.http import HttpResponseRedirect
class ElasticViewSet(viewsets.ModelViewSet):
def my_view(request):
if True:
return HttpResponseRedirect('http://localhost:9200/_seach')
urls.py
router.register(r'elastic', ElasticViewSet, base_name='Elastic')
Traceback
Traceback:
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
83. return self.dispatch(request, *args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
477. response = self.handle_exception(exc)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
437. self.raise_uncaught_exception(exc)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
474. response = handler(request, *args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/generics.py" in get_queryset
67. % self.__class__.__name__
Exception Type: AssertionError at /****/elastic/
Exception Value: 'ElasticViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method.
First thing first, you don't want a ModelViewSet as there's no Model. Just go for the regular ViewSet.
Second, please take some time to think about what you want to do and how you want it done. my_view is not a ViewSet regular action. Returning HttpResponseRedirect is not acting as a proxy.
I'm using python-social-auth to implement twitter login locally but I get the 401 client error. My django version is 1.6.
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/social/apps/django_app/utils.py" in wrapper
45. return func(request, backend, *args, **kwargs)
File "/Library/Python/2.7/site-packages/social/apps/django_app/views.py" in auth
12. return do_auth(request.social_strategy, redirect_name=REDIRECT_FIELD_NAME)
File "/Library/Python/2.7/site-packages/social/actions.py" in do_auth
25. return strategy.start()
File "/Library/Python/2.7/site-packages/social/strategies/base.py" in start
66. return self.redirect(self.backend.auth_url())
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in auth_url
99. token = self.set_unauthorized_token()
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in set_unauthorized_token
158. token = self.unauthorized_token()
File "/Library/Python/2.7/site-packages/social/backends/oauth.py" in unauthorized_token
177. method=self.REQUEST_TOKEN_METHOD)
File "/Library/Python/2.7/site-packages/social/backends/base.py" in request
205. response.raise_for_status()
File "/Library/Python/2.7/site-packages/requests/models.py" in raise_for_status
808. raise HTTPError(http_error_msg, response=self)
Exception Type: HTTPError at /login/twitter/
Exception Value: 401 Client Error: Authorization Required
In documentation it suggests to install ntp.I have no clue how to install ntp.
It turns out I left the callback url field blank in the twitter app console. Although, it's not required, but putting http://127.0.0.1:8000/complete/twitter/ (Note the slash at the end) did the job.
Note also that if you leave the final '/' off the end of the call back URL, you will get this error. It should read
http://127.0.0.1:8000/complete/twitter/
I have a user authentication form in django. Once I login into the form with the super-user credentials, I am having this error : 'DeleteQuery' object has no attribute 'add'
I am using login, REDIRECT_FIELD_NAME, logout methods from the django.contrib.auth module.
This is my Traceback :
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/ramana/enorgo/enorgo/utils/view_functions.py" in wrapper
23. output = func(request, *args, **kw)
File "/home/ramana/enorgo/enorgo/apps/base/views.py" in login
55. login_user(request, form.get_user())
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
83. request.session.cycle_key()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in cycle_key
279. self.delete(key)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in delete
75. Session.objects.get(session_key=session_key).delete()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/base.py" in delete
695. collector.delete()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/deletion.py" in delete
277. query.delete_batch(pk_list, self.using)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/sql/subqueries.py" in delete_batch
47. where.add((Constraint(None, field.column, field), 'in',
Exception Type: AttributeError at /login/
Exception Value: 'DeleteQuery' object has no attribute 'add'
Actually this problem was solved when I shifted to a different database. If someone could explain why this happened, that would be great.
I have a very basic Django class-based view as follows. It doesn't really even do anything:
from django.views.generic import View, TemplateView
class index(TemplateView):
template_name = 'myApp/index.html'
def dispatch(self, request, *args, **kwargs):
return super(index, self).dispatch(request, *args, **kwargs)
However, when I load this view through the browser, I get the following error:
Exception Type: TypeError
Exception Value:
__init__() takes exactly 1 argument (2 given)
Exception Location: /Library/Python/2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/base.py in get_response, line 112
Python Executable: /usr/bin/python
Python Version: 2.7.5
Python Path:
Why am I getting this error? And how to fix it please?
Below is more context around the location of the error:
/Library/Python/2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/base.py in get_response
106. response = middleware_method(request, callback, callback_args, callback_kwargs)
107. if response:
108. break
109. if response is None:
110. wrapped_callback = self.make_view_atomic(callback)
111. try:
112. response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
113. except Exception as e:
114. # If the view raised an exception, run it through exception
115. # middleware, and if the exception middleware returns a
116. # response, use that. Otherwise, reraise the exception.
117. for middleware_method in self._exception_middleware:
118. response = middleware_method(request, e)