how send Firebase Notification in Django admin on save_model - django

Notification are already working in the view class. But not working in admin.py
I do send the puh notification after the save record in save_model. but not working here is my method
class EventAdmin(admin.ModelAdmin):
list_display = ('event_name', 'event_type', 'event_city', 'event_organizer', 'start_date',
'start_time', 'end_date', 'end_time', 'is_approved', 'is_active', 'created_at')
fields = ('main_image', 'event_name', 'event_organizer', 'event_type', 'event_city', 'event_tag', 'event_address', 'event_description',
'event_notes', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_lat', 'event_lng', 'website', 'is_approved', 'is_active', 'created_at')
def save_model(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.created_by:
instance.created_by = user
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
else:
instance.is_updated = True
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
here is my Notification class in admin.py
class Notifications(object):
def sendNotifications(self, data):
users = models.NewEventNotification.objects.all().filter(is_notify=1)
serializer = NewEventNotificationSerializer(users, many=True)
tokens = []
for user in serializer.data:
tokens.append(user['user_token'])
if tokens:
push_service = FCMNotification(api_key=api_key)
message_title = "New Event"
message_body = data
result = push_service.notify_multiple_devices(
registration_ids=tokens, message_title=message_title, message_body=message_body)
print(result)
this shows the result in browser
TypeError at /admin/events/event/add/
Object of type Event is not JSON serializable
Request Method: POST
Request URL: http://192.168.0.104:8000/admin/events/event/add/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
Object of type Event is not JSON serializable
Exception Location: C:\Python\Python37-32\lib\json\encoder.py in default, line 179
Python Executable: C:\Python\Python37-32\python.exe
Python Version: 3.7.4
Python Path:
['D:\\python\\emsbackend',
'C:\\Python\\Python37-32\\python37.zip',
'C:\\Python\\Python37-32\\DLLs',
'C:\\Python\\Python37-32\\lib',
'C:\\Python\\Python37-32',
'C:\\Users\\laptop '
'genration\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages\\pip-19.2.3-py3.7.egg']
Server time: Fri, 20 Dec 2019 18:32:51 +0500
and in console
Internal Server Error: /admin/events/event/add/
Traceback (most recent call last):
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1637, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1564, in _changeform_view
self.save_model(request, new_object, form, not add)
File "D:\python\emsbackend\events\admin.py", line 296, in save_model
notifiClass.sendNotifications(instance)
File "D:\python\emsbackend\events\admin.py", line 382, in sendNotifications
registration_id=tokens[0], message_title=message_title, message_body=message_body)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\fcm.py", line 113, in notify_single_device
**extra_kwargs
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 299, in parse_payload
return self.json_dumps(fcm_payload)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 120, in json_dumps
ensure_ascii=False
File "C:\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Event is not JSON serializable

after searching got this solution. on notification class
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
change to this
# make serializer class of that event
serializer = eventSerializer(instance)
notifiClass = Notifications()
notifiClass.sendNotifications(serializer)

Related

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

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

post() missing 2 required positional arguments: 'self' and 'request'

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'

overriding empty_value_display for specified field not working in django Admin

I have written a model as follows:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3)
birth_date = models.DateField(blank=True, null=True)
And my modeladmin is as follows:
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date')
def view_birth_date(self, obj):
return obj.birth_date
view_birth_date.empty_value_display = '-empty-'
As documented in django 2.1 https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.empty_value_display, I am trying to do this but its not working.
Its gives me fielderror. Even I didn't understand its purpose.
My traceback:
Traceback (most recent call last):
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 703, in get_form
return modelform_factory(self.model, **defaults)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 551, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 266, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (view_birth_date) specified for Author
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1639, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1554, in _changeform_view
ModelForm = self.get_form(request, obj, change=not add)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 707, in get_form % (e, self.__class__.__name__)
django.core.exceptions.FieldError: Unknown field(s) (view_birth_date) specified for Author. Check fields/fieldsets/exclude attributes of class AuthorAdmin.
Does anyone know why this error is coming?
The problem is that you have defined view_birth_date in the fields attribute of model admin class.
Since it is not present in your db model, it is giving error. Such custom fields will work for list_display, in which you can fetch the value from a method as you have done above, see the docs.
Now if you want some custom field to display on the add/change page , you have to create a custom form and there you can define your custom fields.
If the custom field is just for representation , you can define it as readonly as :
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date')
readonly_fields = ['view_birth_date']
def view_birth_date(self, obj):
return obj.title
view_birth_date.empty_value_display = '-empty-'
Hope it helps!

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)