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.
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
models.py
class CustomUser(AbstractUser):
username = PhoneNumberField(unique=True)
payloads:
{
"username": "+8801700000000",
"password1": "demo",
"password2": "demo",
"email": "demo#demo.com",
}
response:
Internal Server Error: /api/rest-auth/registration/
Traceback (most recent call last):
File "venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "venv\lib\site-packages\rest_auth\registration\views.py", line 46, in dispatch
return super(RegisterView, self).dispatch(*args, **kwargs)
File "venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "venv\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "venv\lib\site-packages\rest_auth\registration\views.py", line 65, in create
user = self.perform_create(serializer)
File "venv\lib\site-packages\rest_auth\registration\views.py", line 73, in perform_create
user = serializer.save(self.request)
File "venv\lib\site-packages\rest_auth\registration\serializers.py", line 210, in save
adapter.save_user(request, user, self)
File "venv\lib\site-packages\allauth\account\adapter.py", line 242, in save_user
self.populate_username(request, user)
File "venv\lib\site-packages\allauth\account\adapter.py", line 209, in populate_username
user_username(
File "venv\lib\site-packages\allauth\account\utils.py", line 120, in user_username
return user_field(user, app_settings.USER_MODEL_USERNAME_FIELD, *args)
File "venv\lib\site-packages\allauth\account\utils.py", line 110, in user_field
v = v[0:max_length]
TypeError: 'PhoneNumber' object is not subscriptable
i think this problem because all auth try to subscribe the username by using slicing i recommend to try the following
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
this token from
What's the best way to store Phone number in Django models
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
I am trying to save a post request but I am getting post() missing 2 required positional arguments: 'self' and 'request' error.
View:
class MakeLeaveRequest(generics.CreateAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = MakeLeaveRequestSerializer
# login_url = '../../users/v1/login/'
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid(raise_exception=True):
# self.perform_create(serializer)
date = serializer.save()
print(date)
# headers = self.get_success_headers(serializer.data)
return Response({'ok':'ok'}, status=status.HTTP_201_CREATED)
Serializer:
class MakeLeaveRequestSerializer(serializers.ModelSerializer):
# date_to = serializers.DateField()
# date_from = serializers.DateField()
# description = serializers.CharField()
# types_of_leave = serializers.IntegerField()
class Meta:
model = LeaveRequest
fields = ('date_to', 'date_from', 'description',
'types_of_leave',)
def create(self, validated_data):
user = self.context['request'].user
print(user)
# print(validated_data['date_to'])
try:
LeaveRequest.objects.create(user = user)
except ObjectDoesNotExist:
pass
return user
Trace Path :
admin
2019-01-02
Internal Server Error: /attend/v1/leaveRequest
Traceback (most recent call last):
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/
python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/generics.py", line 192, in post
return self.create(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/attendanceregistersystem/attendance/views.py", line 78, in create
date = serializer.save()
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/attendanceregistersystem/attendance/serializers.py", line 30, in create
LeaveRequest.objects.create(user = user)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send
for receiver in self._live_receivers(sender)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp>
for receiver in self._live_receivers(sender)
TypeError: post() missing 2 required positional arguments: 'self' and
'request'