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

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

Related

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

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

How do I properly deserialize data with django-money?

I have Model that contains MoneyField from djmoney
class Task(models.Model):
description = models.CharField(max_length=512)
user = models.ForeignKey("user.User", on_delete=models.CASCADE)
price = MoneyField(
max_digits=8,
decimal_places=2,
default_currency="USD",
default=0)
Serializer
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = "__all__"
read_only_fields = ("user",)
My APIView POST function of Viewset
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=201, headers=headers)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
When I'm trying to POST data in format like this
{
"description": "Test",
"price": "20.00"
}
It gives me an error, that
'decimal.Decimal' object has no attribute 'amount' with given Traceback.
How can I solve this issue?
Traceback (most recent call last):
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/user/PycharmProjects/my_project/tackapp/tack/views.py", line 37, in create
serializer.is_valid(raise_exception=True)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 426, in run_validation
value = self.to_internal_value(data)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 483, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/fields.py", line 569, in run_validation
self.run_validators(value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/fields.py", line 593, in run_validators
validator(value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/djmoney/models/validators.py", line 30, in __call__
cleaned = cleaned.amount
I did found workaround like this but I'm trying to get my code clean and simple. And I think that I am missing something.
So basically serializer expects value in Money object, but did not expect str from it's own serializer methods
def create(self, request, *args, **kwargs):
price = Money(request.data["price"], "USD")
serializer = self.get_serializer(data=request.data | {"price": price})
...

How to limit serializing in Django Rest Framework?

I have 2 serializers that add and subtract (they are the same, with the difference being add +=1 and subtract -=1) points to an answer. I want to limit them so that a user can only use add point to an answer once. Do you have any idea how to get to it in Django Rest Framework?
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
class SubtractPointsSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('number_of_points',)
def update(self, instance, validated_data):
instance.number_of_points -= 1
instance.save()
return instance
Internal Server Error: /api/v1/answers/2/addpoints
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 226, in put
return self.update(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 68, in update
self.perform_update(serializer)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 78, in perform_update
serializer.save()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 200, in save
self.instance = self.update(self.instance, validated_data)
File "/Users/jakubstrawa/programming/gitlabdeor/api/questions/serializers.py", line 74, in update
if not instance.addition_done and self.request.user not in instance.voters.all():
AttributeError: 'AddPointsSerializer' object has no attribute 'request'
You can always add a Boolean field that stores if addition/subtraction was done. You can store every User that had voted already so noone will vote twice (also will not vote for both +1/-1).
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
addition_done = models.BooleanField(default=False)
subtraction_done = models.BooleanField(default=False)
voters = models.ManyToManyField('User', default=None, blank=True)
===========================================================
class SubtractPointsSerializer(serializers.ModelSerializer):
...
def update(self, instance, validated_data):
if not instance.subtraction_done:
instance.number_of_points -= 1
instance.subtraction_done = True
instance.save()
return instance
You can also divide ManyToMany field into two separated (one for addition, another for subtraction).

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

Django POST request issue with model

I have a model Condition that has a field symptoms, which takes multiple different Symptoms objects. Whenever, I make a POST request to create a Condition object, I get the following error:
'Condition: epilepsy' needs to have a value for field "condition" before this many-to-many relationship can be used.
The above 'Condition: epilepsy' is nested between <>, but theres a formatting issue with posting that.
Here is my Condition model:
class Condition(models.Model):
class Treatment():
SURGERY, NON_INVASIVE, PRESCRIPTION_MEDICINE, NONE = range(4)
CHOICES = (
(SURGERY, 'Surgery'),
(NON_INVASIVE, 'Non-Invasive Treatment'),
(PRESCRIPTION_MEDICINE, 'Prescription Medicine'),
(NONE, 'None')
)
class Medicalfield(models.Model):
ONCOLOGY, CARDIOLOGY, NEPHROLOGY, PEDIATRICS, ENDOCRONOLOGY, PSYCHOLOGY = range(6)
CHOICES = (
(ONCOLOGY, 'Oncology'),
(CARDIOLOGY, 'Cardiology'),
(NEPHROLOGY, 'Nephrology'),
(PEDIATRICS, 'Pediatrics'),
(ENDOCRONOLOGY, 'Endocronology'),
(PSYCHOLOGY, 'Psychology')
)
name = models.CharField(max_length=200)
contagious = models.BooleanField()
treatable = models.BooleanField()
treatment = models.IntegerField(choices=Treatment.CHOICES, null=True)
severeity = models.IntegerField(default=0)
symptoms = models.ManyToManyField('Symptom', blank=True)
medicalfield = models.IntegerField(choices=Medicalfield.CHOICES, null=True)
new = ConditionManager()
def __unicode__(self):
return u"%s" % ( self.name )
Here is my Serializer
class ConditionSerializer(serializers.ModelSerializer):
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
Here is the Manager
class ConditionManager(models.Manager):
use_in_migrations = True
use_for_related_fields=True
def create_condition(self, *args, **kwargs):
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
condition_obj.save()
return condition_obj
And here is the View
#api_view(['POST'])
#permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
symptoms = request.data['symptoms']
symptoms = Symptom.objects.filter(name__in=symptoms)
s = []
for symptom in symptoms:
s.append(symptom.pk)
request.data['symptoms'] = s
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/Users/user/medicalrecords/conditions/views.py", line 28, in create_condition
serializer.save()
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/Users/user/medicalrecords/conditions/serializers.py", line 24, in create
return Condition.new.create_condition(**attrs)
File "/Users/user/medicalrecords/conditions/managers.py", line 17, in create_condition
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 550, in __init__
setattr(self, prop, kwargs[prop])
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
manager = self.__get__(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
(instance, self.source_field_name))
ValueError: "<Condition: epilepsy>" needs to have a value for field "condition" before this many-to-many relationship can be used.
[22/Feb/2017 20:01:45] "POST /conditions/new/condition/ HTTP/1.1" 500 15799
traceback from #snakefcz 's answer
Internal Server Error: /conditions/new/condition/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/Users/user/medicalrecords/conditions/views.py", line 45, in create_condition
return response.Response(serializer.data, status=201)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 527, in data
ret = super(Serializer, self).data
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 496, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 643, in to_representation
self.child.to_representation(item) for item in iterable
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 479, in to_representation
fields = self._readable_fields
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in get
res = instance.dict[self.name] = self.func(instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 373, in _readable_fields
field for field in self.fields.values()
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 359, in fields
for key, value in self.get_fields().items():
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 1010, in get_fields
fields[field_name] = field_class(**field_kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/fields.py", line 733, in init
super(CharField, self).init(**kwargs)
TypeError: init() got an unexpected keyword argument 'view_name'
You'll need to create a Symptom serializer in addition to the Condition one. Your ConditionSerializer should look something like:
class ConditionSerializer(serializers.ModelSerializer):
symptoms = SymptomSerializer(read_only=True, many=True, allow_null=True)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
## Try it
#api_view(['POST'])
#permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
condition = serializer.save()
symptoms = request.data['symptoms']
for symp in symptoms:
symptom = Symptom.objects.get(id=symp) ## if it's id's you are passing
condition.symptoms.add(symptom)
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)