I am trying to set-up email verification using django-rest-knox. The link is being sent out. When I use the following:
from knox.auth import TokenAuthentication
class VerifyEmailAPI(generics.GenericAPIView):
def get(self, request):
# Get the token from request
# token = request.GET.get('token')
# print(token)
user = TokenAuthentication.authenticate(request, self)
print(user)
return Response({'message': 'Just testing for now'})
The url:
http://127.0.0.1:8000/api/auth/email-verify/?token=58cab01ad07801dbe5e6c4fc5c6c7ef060bf7912cb723dc70e4c5fb677fbbf1e
I get this error:
AttributeError: 'VerifyEmailAPI' object has no attribute 'META'
Complete traceback:
Traceback (most recent call last):
File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Volumes/coding/fort_dev/accounts/api.py", line 75, in get
user = TokenAuthentication.authenticate(request, self)
File "/Users/sid/eb-virt/lib/python3.8/site-packages/knox/auth.py", line 37, in authenticate
auth = get_authorization_header(request).split()
File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/authentication.py", line 20, in get_authorization_header
auth = request.META.get('HTTP_AUTHORIZATION', b'')
AttributeError: 'VerifyEmailAPI' object has no attribute 'META'
Am I doing something fundamentally wrong when using the django-rest-knox function?
Related
i have created this serializer to validate on the presence of a record with these column combination`
class CampaignServicesValidation(serializers.Serializer):
campaign_id = serializers.IntegerField(required=True)
service_id = serializers.IntegerField(required=True)
def validate(self, data):
try:
campaign_service = CampaignServices.objects.get(campaign_id=data['campaign_id'],
service_id=data['service_id'])
print("found"+str(campaign_service.id))
except Exception:
raise serializers.ValidationError(detail='Campaign Service does not exist')
return campaign_service
and it is called in my viewSet like this:
campaign_service = CampaignServicesValidation(data={'campaign_id': request.data['campaign_id'], 'service_id': pk})
if not campaign_service.is_valid():
return RestResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, serializer_error=campaign_service.errors)
when the combination is not found it raises an exception and works well, but when it passes validation and enters the is_valid() function in the if condition it produces this error
Traceback (most recent call last):
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\RightsHero\collector-management\collectors_management\views.py", line 157, in update_campaign_service_frequency
serializer.save()
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 993, in update
info = model_meta.get_field_info(instance)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'CampaignServicesValidation' object has no attribute '_meta'
I have tried changing serializer.Serializer to ModelSerialzier but nothing changed
Since Serializer does not have a _meta attribute, it does not have the is_valid() method. Instead, you should check the serializer.errors attribute of the serializer after calling validate().
I am doing my first Django MongoDB project and trying to save the data set in the database
here is the create method that I'm using
def create(self, request, *args, **kwargs):
try:
client = MongoClient('srv13.absolute.ag:27017')
collection = client.farmos.device
header = request.headers['Authorization']
req = json.loads(request.body)
resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header)
device_id = resp.headers['Location'][8:]
req['device_token'] = device_id
collection.insert_one(req)
return {'data': 'Success'}, 200
except Exception as e:
return {'data': str(e)}, 400
But it showing an error
and the error is
Internal Server Error: /api/v1/device/
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/adarsh/farmos/farmos/persistance_layer/mongodb/device_operations.py", line 53, in create
response = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=json.dumps(req), headers=header)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/api.py", line 117, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/sessions.py", line 515, in request
prep = self.prepare_request(req)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/sessions.py", line 453, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/models.py", line 319, in prepare
self.prepare_headers(headers)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/models.py", line 451, in prepare_headers
for header in headers.items():
AttributeError: 'str' object has no attribute 'items'
I think there is a problem in this line
python
resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header)
I have tried different thing changing the type of req and header to solve it but couldn't do it
I have the following in adapter.py:
from allauth.account.adapter import DefaultAccountAdapter
class CustomAllauthAdapter(DefaultAccountAdapter):
pass # keeping it trivial for debugging
At the very bottom of settings.py:
import django
django.setup() # complains about apps not being loaded yet without this...
from .adapter import CustomAllauthAdapter
ACCOUNT_ADAPTER = CustomAllauthAdapter # this is the line that results in the error!
As soon as I submit the registration form for a new user, I get this error in the browser:
AssertionError at /api/v1/users/auth/register/
No exception message supplied
Here is the Traceback:
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch
return super().dispatch(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 66, in create
serializer.is_valid(raise_exception=True)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 478, in to_internal_value
validated_value = validate_method(validated_value)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\serializers.py", line 209, in validate_email
email = get_adapter().clean_email(email)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\account\adapter.py", line 535, in get_adapter
return import_attribute(app_settings.ADAPTER)(request)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\utils.py", line 153, in import_attribute
assert isinstance(path, str)
If I do not set the ACCOUNT_ADAPTER, everything works well including registration and authentication. I need to use custom account adapter to customize email verification.
Why am I getting the error and what should I do to fix it?
No need to import anything and no need for django.setup(). The configuration variable is a string!
ACCOUNT_ADAPTER = 'users.adapter.CustomAllauthAdapter'
I am creating an API for signup.
Serializers.py
class UserSignupSerializer(serializers.Serializer):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'role']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validate_data):
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
user.set_password(validate_data['password'])
user.save()
return user
Views.py
class UserSignupView(APIView):
def post(self, request):
serializer = UserSignupSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
But this is giving key error 'email' or anything I put first in this line:
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
Edit
Error
Internal Server Error: /api/user_signup/
Traceback (most recent call last):
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 468, in raise_uncaught_exception
raise exc
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\views.py", line 187, in post
serializer.save()
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\serializers.py", line 213, in save
self.instance = self.create(validated_data)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\serializers.py", line 85, in create
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
KeyError: 'email'
[2019-09-03 11:49:43,186] log: ERROR - Internal Server Error: /api/user_signup/
Traceback (most recent call last):
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 468, in raise_uncaught_exception
raise exc
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\views.py", line 187, in post
serializer.save()
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\serializers.py", line 213, in save
self.instance = self.create(validated_data)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\serializers.py", line 85, in create
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
KeyError: 'email'
[03/Sep/2019 11:49:43] "POST /api/user_signup/?username=user_4&last_name=user&first_name=user&email=u#gmail.com&password=user&role=user HTTP/1.1" 500 18553
I think you should use serializers.Modelserializer instead of serializers.Serializer.
I am using django-rest-auth registration api, I overridden that by using my own SERIALIZER and model. So I am getting error.
I have tried by setting active at the time user created. But that is not working.
Let me know how to resolve this type of problem.
[12/Jan/2019 17:24:06] "POST /rest-auth/registration/ HTTP/1.1" 400 68
Internal Server Error: /rest-auth/registration/
Traceback (most recent call last):
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 46, in dispatch
return super(RegisterView, self).dispatch(*args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/generics.py", line 192, in post
return self.create(request, *args, **kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 65, in create
user = self.perform_create(serializer)
File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 81, in perform_create
None)
File "/Users/test/project/vblah/lib/python3.6/site-packages/allauth/account/utils.py", line 183, in complete_signup
signal_kwargs=signal_kwargs)
File "/Users/test/project/vblah/lib/python3.6/site-packages/allauth/account/utils.py", line 133, in perform_login
return adapter.respond_user_inactive(request, user)
File "/Users/test/project/vblah/lib/python3.6/site-packages/allauth/account/adapter.py", line 454, in respond_user_inactive
reverse('account_inactive'))
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/test/project/vblah/lib/python3.6/site-packages/django/urls/resolvers.py", line 622, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'account_inactive' not found. 'account_inactive' is not a valid view function or pattern name.```
this exception happend because in your User model
is_active = False .
so set True and migrate
in models.py set is_active = True
and migrate the tables