AttributeError: 'Serializer' object has no attribute '_meta' - django

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().

Related

django-rest-knox - how to authenticate token for email verification?

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?

KeyError at /api/rooms/create-grade/ 'grade'

I don't understand this error one bit, I'm trying to do a basic create method but I get a KeyError what am i doing wrong
This is serializer.py code
class GradeCreateSerializer(serializers.ModelSerializer):
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
class Meta:
model = Grade
fields = ["grade"]
# ordering = ['-created_date']
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
try:
perms = Perm.objects.get(user=user)
except:
perms = None
if user.role in ['OWNER', 'PARTNER']:
school = user.owns.first()
elif perms is not None:
if user.role == 'STAFF' and perms.can_crt_grade_class:
school = user.works
instance = Grade.objects.create(
grade=validated_data['grade'],
school=school,
)
instance.save()
return instance
what am I doing wrong??
I have added the error traceback as requested
error traceback
Traceback (most recent call last):
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "F:\Projects\SchoolProject\main\Classes\serializers.py", line 45, in create
grade=validated_data['grade'],
KeyError: 'grade'
it says that grade=validated_data['grade'], this the problem but i don't get it.
I have found a solution to my issue, it was because of grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display") this means when using a ChoiceField to define your field you don't need to pass the source="" as the field uses the choice to determine it
So changing
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
to
grade = serializers.ChoiceField(choices=GRADES)
did the trick

requests.post(url, data)error `Response`, `HttpResponse` or `HttpStreamingResponse` but received a `<class 'tuple'>`

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

'int' object has no attribute 'user_list'. (Django Rest Framework)

I have a feature where user can remove an item from a list. The code below does successfully remove (delete) the item from the list but also returns the following error (and my AJAX call doesn't complete successfully):
Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_list'.
I am not sure how to debug this/why this error is being thrown.
Here is my serializers:
class UserVenueSerializer(serializers.ModelSerializer):
venue = mapCafesSerializer()
class Meta:
model = UserVenue
fields = ['user_list', 'venue']
Here is my views
class RemoveVenueViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserVenueSerializer
authentication_classes = [CsrfExemptSession]
def get_queryset(self):
user_list = self.request.GET.get('user_list', None)
venue = self.request.GET.get('venue', None)
data = UserVenue.objects.filter(user_list = user_list, venue= venue)
print(data)
return data.delete()
Here is the traceback:
<QuerySet [<UserVenue: UserVenue object (142)>]>
Internal Server Error: /api/removevenue/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'int' object has no attribute 'user_list'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
return Response(serializer.data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data
ret = super().data
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation
return [
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 502, in to_representation
attribute = field.get_attribute(instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 190, in get_attribute
return super().get_attribute(instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 490, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_list'
I'd be grateful for any advice!
you can try this method
class RemoveVenueViewSet(APIView):
serializer_class = serializers.UserVenueSerializer
authentication_classes = [CsrfExemptSession]
def delete(self, request, *args, **kwargs):
user_list = request.GET.get('user_list', None)
venue = request.GET.get('venue', None)
success = UserVenue.objects.filter(user_list=user_list, venue=venue).delete()
if success:
return Response("Question deleted", status=status.HTTP_204_NO_CONTENT)
return Response("Item does not exixt", status=status.HTTP_404_NOT_FOUND)
I ended up just using vanilla Django and it worked like a charm.
def remove_venue_from_list(request):
user_list = request.GET.get('user_list', None)
venue = request.GET.get('venue', None)
data = UserVenue.objects.filter(user_list = user_list, venue = venue)
data.delete()
return render(request, 'testingland/index3.html')

create method is raising key error in serializer

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.