How to fix Key Error when testing django create CBV? - django

I have been troubleshooting this problem for 3 days now. I think I'm missing something fundamental about testing Create Views or using client.post().
The test is failing because the date key is not present in the cleaned_data dictionary of the form, however, the code works correctly when executed from the browser.
Can you please tell me why is the date key present in the cleaned_data dictionary when running in the browser but absent when executed by client.post() in the test?
Below are snippets of relevant code.
Models.py
class Livestock(CommonInfo):
"""Model definition for Livestock. CommonInfo is an abstract model that contains
created_by, modified_by, date_created, date_modified and comment fields"""
product = models.ForeignKey(
Product, on_delete=models.CASCADE, related_name='livestock')
date = models.DateField(
auto_now=False, auto_now_add=False)
production = models.PositiveIntegerField(
'Livestock produced (Kg or litre or #)')
number_of_animal = models.PositiveIntegerField(
'Number of Animals (Quantity)', blank=True, null=True)
cost_of_production = models.PositiveIntegerField(
'Cost of Production (GYD)', blank=True, null=True)
views.py
class LivestockCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Livestock
form_class = LivestockForm
success_url = reverse_lazy('real:livestock-list')
template_name = "real/livestock/livestock_form.html"
permission_required = ('real.add_livestock')
def get_initial(self):
initial = super(LivestockCreateView, self).get_initial()
initial['date'] = timezone.now()
return initial
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
Forms.py
class LivestockForm(forms.ModelForm):
"""Form definition for Livestock."""
class Meta:
"""Meta definition for Livestockform."""
model = Livestock
fields = ['product', 'date', 'production',
'number_of_animal', 'cost_of_production', 'comment',
'modified_by', 'created_by']
widgets = {
'date': forms.DateInput(attrs={'type': 'date'}),
'modified_by': forms.HiddenInput(),
'created_by': forms.HiddenInput(),
}
def clean(self):
self.cleaned_data = super(LivestockForm, self).clean()
self._validate_unique = True
self.cleaned_data['date'] = self.cleaned_data['date'].replace(day=1)
return self.cleaned_data
test.py
class LivestockTests(TestCase):
#classmethod
def setUpTestData(cls):
cls.User = get_user_model()
cls.user = cls.User.objects.create_user(
username='test_user',
password='testpass123',
first_name='test',
last_name='user'
)
cls.product = Product.objects.create(
name='Milk'
)
def test_livestock_create_view_user_is_login_and_have_permission(self):
self.user.user_permissions.add(
Permission.objects.get(codename='add_livestock'))
login = self.client.login(username='test_user', password='testpass123')
response = self.client.post((reverse('real:livestock-create'),
{'product': self.product.id,
'date': timezone.now(),
'production': 5200
})
view = resolve('/sector/real/livestock/create')
self.assertTrue(login)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'real/livestock/livestock_form.html')
self.assertContains(response, 'Livestock')
self.assertNotContains(response, 'Sugar')
self.assertEqual(
view.func.__name__,
views.LivestockCreateView.as_view().__name__
)
traceback
D:\MOF\Projects\guyanaeconomicsectoranalysis>docker-compose exec web python manage.py test real
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.E............
======================================================================
ERROR: test_livestock_create_view_user_is_login_and_have_permission
(real.tests.tests_livestock.LivestockTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Projects/real/tests/tests_livestock.py", line 875, in
test_livestock_create_view_user_is_login_and_have_permission
'production': 5200
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 357, in post
secure=secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 85, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/edit.py", line 141, in post
if form.is_valid():
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 382, in full_clean
self._clean_form()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 409, in _clean_form
cleaned_data = self.clean()
File "/Projects/real/forms.py", line 140, in clean
self.cleaned_data['date'] = self.cleaned_data['date'].replace(day=1)
KeyError: 'date'
----------------------------------------------------------------------
Ran 14 tests in 0.791s
FAILED (errors=1)
Destroying test database for alias 'default'...
Proof Code working in browser

Related

type object 'Task' has no attribute '_meta'

Am starter in Django and tried CreateView class and got the following error: Am unable to find the issue. ListView and DetailView works fine.
Trace Log :
System check identified no issues (0 silenced).
July 20, 2022 - 22:38:33
Django version 3.2.12, using settings 'configs.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /task/create/
Traceback (most recent call last):
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 32, in get_form
form_class = self.get_form_class()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 563, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 261, in __new__
fields = fields_for_model(
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 150, in fields_for_model
opts = model._meta
AttributeError: type object 'Task' has no attribute '_meta
model :
class Task(models.Model):
user =models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='usertasks')
title = models.CharField(max_length=200,blank=False, null=False)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
create = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('task-app:task', kwargs={'pk': self.pk})
def __unicode__(self):
return self.title
class Meta:
ordering = ['-create']
view :
class TaskCreate(CreateView):
model = Task
# fields = "__all__"
fields = ('title', 'description')
# fields = ['title']#,'description','completed']
success_url= reverse_lazy('task-app:tasks')
Dear All the issue is Task is Key-word and so causing issue. I renamed the model as alltask and it fixed the issue. Though this is not faced by all, but can be useful if no solution found.

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

Multiple objects returned in Django

So I have my code below, whenever I run it in admin and try to view that object returns and error:
Exception Type: MultipleObjectsReturned
Exception Value:
get() returned more than one c2 -- it returned 2!
How do I resolve this error?
models.py:
from django.db import models
import datetime
import pytz
from django.utils import timezone
class c1(models.Model):
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class c2(models.Model):
c1 = models.ForeignKey(c1, on_delete=models.CASCADE)
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class c3(models.Model):
c2 = models.ForeignKey(c2, on_delete=models.CASCADE)
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class Task_manager(models.Manager):
def create_Task(self, title):
Task1 = self.create(title=title)
return Task1
class Task(models.Model):
STATUS = (
('ONGOING', 'ONGOING'),
('COMPLETED','COMPLETED'),
)
search=models.CharField(max_length=300, choices=search_title, default="OTHER")
c1=models.ForeignKey(c1, on_delete=models.SET_NULL, null=True)
c2=models.ForeignKey(c2, on_delete=models.SET_NULL, null=True)
c3=models.ForeignKey(c3, on_delete=models.SET_NULL, null=True)
title=models.CharField(max_length=30,default="Other")
created=models.DateTimeField(default=timezone.now())
objects=Task_manager()
class Meta:
ordering = [ '-created']
def __str__(self):
return self.title
Here is my ModelAmdin class in admin.py
admin.py snippet:
class TaskAdmin(admin.ModelAdmin):
film_status.allow_tags = True'''
form=TaskForm
list_filter=('c1')
readonly_fields = ['score','score_fixed','deadline_fixed','created']
def change_view(self,request,object_id,extra_content=None):
return super(TaskAdmin,self).change_view(request,object_id)
admin.site.register(Task,TaskAdmin)
admin.site.register(c1)
admin.site.register(c2)
admin.site.register(c3)
You can also have a look at TaskForm class.
forms.py:
class TaskForm(forms.ModelForm):
class Meta:
model=Task
fields='__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['c1'].queryset = c1.objects.all()
self.fields['c2'].queryset = c2.objects.get()
self.fields['c3'].queryset = c3.objects.none()
Here is the full error for the code:
Traceback (most recent call last):
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "C:\My_Django_stuff\tada\todo\tasks\admin.py", line 64, in change_view
return super(TaskAdmin,self).change_view(request,object_id)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1641, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1582, in _changeform_view
form = ModelForm(instance=obj)
File "C:\My_Django_stuff\tada\todo\tasks\forms.py", line 14, in __init__
self.fields['c2'].queryset = c2.objects.get()
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 419, in get
raise self.model.MultipleObjectsReturned(
Exception Type: MultipleObjectsReturned at /admin/tasks/task/9/change/
Exception Value: get() returned more than one c2 -- it returned 2!
QuerySet.get() will raise an exception if the queryset does not contain exactly one object. Either an DoesNotExist or an MultipleObjectsReturned. This is by design.
You can handle this by using a try, except, of by calling another QuerySet method (.first() to get first object, for instance).

Object of type JSON non serializable django REST Framwork

Hi guys I am having the error Object of type 'MyUser' is not JSON serializable, I checke on many post that has the same issue but nothing seems to make my code work
Could someone help me please ?
in my views:
class TeamChartData(APIView):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
permission_classes = []
http_method_names = ['get',]
def get_serializer_class(self):
return self.serializer_class
def get(self, request, format=None, *args, **kwargs):
chunk_team = get_chunk_team(self)
data = {
"chunk_team":chunk_team
}
return Response(data)
def get_chunk_team(self, format=None, *args, **kwargs):
current_team_member = Project.objects.get(id = self.kwargs['pk']).team_id.members.all()
print(current_team_member)
return current_team_member
serializer.py :
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from registration.models import MyUser
from website.models import Team,Project
from survey.models import Response
class MyUserSerializer(ModelSerializer):
team = serializers.SerializerMethodField()
class Meta:
model = MyUser
fields = (
'email',
'first_name',
'last_name',
'team',
)
def get_team(self, obj):
#print(obj) # for you to understand what's happening
teams = Team.objects.filter(members=obj)
serialized_teams = TeamSerializer(teams,many=True)
return serialized_teams.data
class TeamSerializer(ModelSerializer):
class Meta:
model = Team
fields = (
'team_name',
'team_hr_admin',
'members',
)
I added my log in order for you to have a look on what is going on behing the scenes
log:
<QuerySet [<MyUser: rise1#gmail.com>, <MyUser: rise2#gmail.com>, <MyUser: rise3#gmail.com>]>
Internal Server Error: /website/project/2/api/chart/data2/
Traceback (most recent call last):
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", li
ne 41, in inner
response = get_response(request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 21
7, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 21
5, in _get_response
response = response.render()
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/template/response.py", line 107
, in render
self.content = self.rendered_content
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/response.py", line 72,
in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/renderers.py", line 706
, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/renderers.py", line 664
, in get_context
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/renderers.py", line 411
, in get_content
content = renderer.render(data, accepted_media_type, renderer_context)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/renderers.py", line 105
, in render
separators=separators
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 430, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 438, in _iterencode
yield from _iterencode(o, _current_indent_level)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 428, in _iterencode
yield from _iterencode_list(o, _current_indent_level)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 325, in _iterencode_list
yield from chunks
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 437, in _iterencode
o = _default(o)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/rest_framework/utils/encoders.py", lin
e 70, in default
return super(JSONEncoder, self).default(obj)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'MyUser' is not JSON serializable
[21/Dec/2017 14:49:11] "GET /website/project/2/api/chart/data2/ HTTP/1.1" 500 158505
The Corresponding view would be as follows:
class TeamChartData(APIView):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
permission_classes = []
http_method_names = ['get',]
def get_serializer_class(self):
return self.serializer_class
def get(self, request, format=None, *args, **kwargs):
chunk_team = get_chunk_team(self)
chunk_team = MyUserSerializer(chunk_team).data #included line
data = {
"chunk_team":chunk_team
}
return Response(data)
def get_chunk_team(self, format=None, *args, **kwargs):
current_team_member = Project.objects.get(id = self.kwargs['pk']).team_id.members.all()
print(current_team_member)
return current_team_member

Serializer results in KeyError after correct data input and save

I'm creating an API endpoint that works and saves data through its API. It works, but my concern is that it throws a KeyError as shown below. I'm not sure if this is an issue with my code. Your help is very much appreciated.
Data:
data = {'title': u'abc', 'career_level': 1}
Serializer:
class JobPostSerializer(serializers.ModelSerializer):
career_level = PrimaryKeyRelatedField(allow_null=True, queryset=CareerLevel.objects.all(), required=False)
title = CharField(allow_blank=True, allow_null=True, max_length=240, required=False)
Model:
class JobPost(models.Model):
career_level = models.ForeignKey(CareerLevel, related_name='jobpost_career', blank=True, null=True)
title = models.CharField(max_length=240, blank=True, null=True)
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
class Meta:
ordering = ['-created_at']
Error Message:
Internal Server Error: /api/v1/posts/
Traceback (most recent call last):
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 87, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 22, in create
headers = self.get_success_headers(serializer.data)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 503, in data
ret = super(Serializer, self).data
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 241, in data
self._data = self.to_representation(self.validated_data)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 463, in to_representation
attribute = field.get_attribute(instance)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/relations.py", line 157, in get_attribute
return get_attribute(instance, self.source_attrs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/fields.py", line 78, in get_attribute
instance = instance[attr]
KeyError: u'career_level'
Your serializer definition makes no sense.
JobPostSerializer(data={'title': u'abc', 'career_level': 1}):
It should instead be:
class JobPostSerializer(serializers.ModelSerializer):
That line of yours is more similar to when you want to instantiate the serializer. Something like when you want to check if the input was valid, for example.
job_serializer = JobPostSerializer(data={'title': u'abc', 'career_level': 1})
job_serializer.is_valid()