Django Serializer is not JSON serializable - django

I'm trying to serialize an object details which contains ForeignKey and OneToOneField.
Here is my Model:
user = models.OneToOneField(
"User",
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="User",
help_text="The user who subscribed.",
related_name="subscription_information",
unique=True,
)
subscription = models.ForeignKey(
Subscription,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="subscription_information",
verbose_name="Subscription",
help_text="This is the subscription.",
)
subscription_type = models.IntegerField(
choices=SUBSCRIPTION_TYPES_CHOICES,
default=SubscriptionTypes.monthly,
null=False,
blank=False,
verbose_name="Subscription Type",
help_text="",
)
next_payment_amount = models.FloatField(
default=0.0,
null=False,
blank=True,
verbose_name="Subscription Plan Next Payment Amount",
help_text=(""),
)
next_payment_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Next Payment Date",
help_text=(""),
)
payment_made = models.BooleanField(
null=False,
blank=True,
default=False,
verbose_name="Is Payment Made",
help_text=(
""
),
)
subscription_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Subscription Date",
help_text="",
)
As you see User field is OneToOneField and Subscription field is foreign key.
And here is my serializer:
class SubscriptionInformationDetailSerializer(serializers.ModelSerializer):
class Meta:
model = SubscriptionInformation
fields = (
"id",
"user",
"subscription",
"subscription_type",
"next_payment_amount",
"next_payment_date",
"payment_made",
"subscription_date",
)
I want to return serialized SubscriptionInformation with this code:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer
But it throws this error:
Traceback (most recent call last):
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
response = response.render()
File "E:\Programming\project\venv\lib\site-packages\django\template\response.py", line 109, in render
self.content = self.rendered_content
File "E:\Programming\project\venv\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\renderers.py", line 105, in render
allow_nan=not self.strict, separators=separators
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "C:\Python27\Lib\json\__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\Lib\json\encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\Lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "C:\Python27\Lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: DetailSerializer(<Thing: Thing object>, read_only=True):
id = IntegerField(label='ID', read_only=True)
user = PrimaryKeyRelatedField(help_text='The user who subscribed.', queryset=User.objects.all(), validators=[<UniqueValidator(queryset=SubscriptionInformation.objects.all())>])
subscription = PrimaryKeyRelatedField(help_text='This is the subscription.', queryset=Subscription.objects.all())
subscription_type = ChoiceField(choices=((0, 'Monthly'), (1, 'Annual')), help_text='', label='Subscription Type', required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
next_payment_amount = FloatField(help_text='', label='Subscription Plan Next Payment Amount', required=False)
next_payment_date = DateTimeField(allow_null=True, help_text='', label='Next Payment Date', required=False)
payment_made = BooleanField(help_text='', label='Is Payment Made', required=False)
subscription_date = DateTimeField(allow_null=True, help_text='', label='Subscription Date', required=False) is not JSON serializable
I couldn't understand why can't I serialize this. Why it's not JSON serializable

Ok, No problem with model and serializer. I just need to return the serializer.data. So my code should be like that:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer.data

Related

how to get user's last login with OneToOneField and display it on admin panel?

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'portal_users.admin.ProfileAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'user__last_login', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'portal_users.Profile'.
System check identified 1 issue (0 silenced).
There is my code
models.py:
class Profile(models.Model):
user = models.OneToOneField(
User,
null=True,
related_name='profile',
on_delete=CUSTOM_SET_NULL,
)
student_id = models.IntegerField(
blank=True,
null=True,
verbose_name='ID студента/преподавателя',
help_text='Из 1С',
)
first_name = models.CharField(
max_length=200,
verbose_name='Имя',
blank=True,
)
last_name = models.CharField(
max_length=200,
verbose_name='Фамилия',
blank=True,
)
admin.py:
#admin.register(models.Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = [
'user',
'first_name',
'last_name',
'user__last_login',
]
You would need to add a custom method that would display the last login on admin:
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user','first_name', 'last_name', 'get_last_login']
def get_last_login(self,instance):
return instance.user.last_login
get_last_login.short_description = "Last login"
More on this: Documentation on list_display

Django Unitest, can't recognize the error

I am wondering if could anyone help out here, I am trying to send a post request to the URL, but I am not sure about the best way of doing it?
The idea here is to test the creation of the card object, but I am getting an error which I am not managing to figure out, if anyone could help me out here it would be fantastic.
here the code and the error below it
def test_create_card(self):
payload = {
'title': "Sample card title",
'description': 'Get a free coffee for every 10 coffee you buy',
'points_needed': 10,
}
res = self.client.post(CARDS_URL, self.company, **payload)
print(res)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
card = Card.objects.get(id=res.data['id'])
for k, v in payload.items():
self.assertEqual(getattr(card, k), v)
self.assertEqual(card.company, self.company)
ERROR
ERROR: test_create_card (card.tests.test_card_api.PrivateCardAPITests)
Test creating a card
Traceback (most recent call last):
File "/app/card/tests/test_card_api.py", line 141, in test_create_card
res = self.client.post(CARDS_URL, self.company, **payload)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post
response = super().post(
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 208, in post
data, content_type = self._encode_data(data, format, content_type)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 179, in _encode_data
ret = renderer.render(data)
File "/py/lib/python3.9/site-packages/rest_framework/renderers.py", line 914, in render
return encode_multipart(self.BOUNDARY, data)
File "/py/lib/python3.9/site-packages/django/test/client.py", line 245, in encode_multipart
for (key, value) in data.items():
AttributeError: 'Company' object has no attribute 'items
'
and here is the model:
'
class Card(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
description = models.TextField(blank=True)
points_needed = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
'

The value of 'list_display[5]' must not be a ManyToManyField

I am trying to create manytomany fields in one of the class, I am getting an error "The value of 'list_display[5]' must not be a ManyToManyField"
Need Help, Thanks in advance :)
class ShiftConfig(models.Model):
description = models.CharField(max_length=30)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return str(self.id) + ' : ' + str(self.start_time)
class FaultConfig(models.Model):
description = models.CharField(max_length=30)
message = models.ForeignKey(Message, null=True, on_delete=models.SET_NULL)
recipients = models.ForeignKey(UserGroup, null=True, on_delete=models.SET_NULL)
alert_time = models.DurationField(default=timedelta(0.0001))
repeat = models.PositiveSmallIntegerField()
escalated_fault = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, blank=True)
def __str__(self):
return str(self.id) + ' : ' + str(self.description)
Here is the concerned class.
class WorkStation(models.Model):
name = models.CharField(max_length=30)
location = models.CharField(max_length=30)
department= models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)
current_user=models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
allowed_fault_configs = models.ManyToManyField(FaultConfig, through='WFMembership', through_fields=('workstation', 'fault_config'))
allowed_shift_configs = models.ManyToManyField(ShiftConfig, through='WSMembership', through_fields=('workstation', 'shift_config'))
def __str__(self):
return str(self.id) + ' : ' + str(self.name)
class WFMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
fault_config = models.ForeignKey(FaultConfig, on_delete=models.CASCADE)
class WSMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
shift_config = models.ForeignKey(ShiftConfig, on_delete=models.CASCADE)
Here is the error which mentions that the field must not be ManyToManyField
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\channels\management\commands\runserver.py", line 69, in inner_run
self.check(display_num_errors=True)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 441, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField.
System check identified 2 issues (0 silenced).
Here is the admin.py for Workstation
#admin.register(WorkStation)
class WorkStation(admin.ModelAdmin):
list_display = ('id', 'name','location','department','current_user','allowed_fault_configs', 'allowed_shift_configs')
list_display_links = ('id', 'name')
Can you post your admin.py? Specifically andon.admin.WorkStation?
Please refer to Django documentation for ManytoManyField usage in admin console.
You can write a custom function to retrieve those values from the ManyToManyField.

Django rest framework: error when post() for foreign key

I am trying to do simple get() post() to my database. I have existing database and I used inspectdb to generate the models.py from it. I am facing issue with setting up composite primary key for a model and a part of that keys are foreign key
The model TestCase has foreign key relation with TestSuite model. The get() to TestCase api works well. However the post fails with below error:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
20. serializer.is_valid(raise_exception=True)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in run_validation
434. value = self.to_internal_value(data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_internal_value
491. validated_value = field.run_validation(primitive_value)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in run_validation
160. return super(RelatedField, self).run_validation(data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/fields.py" in run_validation
536. value = self.to_internal_value(data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in to_internal_value
263. return self.get_queryset().get(pk=data)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in get
407. (self.model._meta.object_name, num)
Exception Type: MultipleObjectsReturned at /dqf_api/test_case/
Exception Value: get() returned more than one TestSuite -- it returned
2!
Request information:
USER: AnonymousUser
The browsable api calls also fail with above error
models.py
class TestCase(models.Model):
team_name = models.ForeignKey(TestSuite, on_delete=models.DO_NOTHING, db_column='team_name')
suite_name = models.ForeignKey(TestSuite, on_delete=models.DO_NOTHING, db_column='suite_name')
case_name = models.CharField(max_length=100, primary_key=True)
test_type = models.ForeignKey(TestCaseType, on_delete=models.DO_NOTHING)
class Meta:
managed = False
db_table = 'test_case'
unique_together = (('team_name', 'suite_name', 'case_name'),)
class TestSuite(models.Model):
team_name = models.ForeignKey(Team, on_delete=models.DO_NOTHING, db_column='team_name')
suite_name = models.CharField(max_length=100, primary_key=True)
description = models.CharField(max_length=200, blank=True, null=True)
#Additional fields
class Meta:
managed = False
db_table = 'test_suite'
unique_together = (('team_name', 'suite_name'),)
class TestCaseType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=200, blank=True, null=True)
class Meta:
managed = False
db_table = 'test_case_type'
class Team(models.Model):
team_name = models.CharField(primary_key=True, max_length=30)
description = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'team'
views.py
class TestCaseViewSet(viewsets.ModelViewSet):
queryset = models.TestCase.objects.all()
serializer_class = serializers.TestCaseSerializer
class TestSuiteViewSet(viewsets.ModelViewSet):
queryset = models.TestSuite.objects.all()
serializer_class = serializers.TestSuiteSerializer
serializers.py
class TestSuiteSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestSuite
fields = '__all__'
class TestCaseSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCase
fields = '__all__'
data.json
{
"case_name": "NA",
"description": "NA",
"run_level": 1,
"stop_on_failure": false,
"team_name": "ede",
"suite_name": "dummy",
"test_type": 1
}
Only one record with team_name =ede and suite_name = dummy is present in the test_suite table
I am new to Django and DRF. Any help is appreciated.

Error when migrating new User model

Just created a User model in my models.py to save the users in the database. The model looks like this:
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30, unique=True,
validators=[
validators.RegexValidator(re.compile('^[\w.#+-]+$'), _('Enter a valid username.'), _('invalid'))
])
first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
email = models.EmailField(_('email address'), max_length=255)
is_staff = models.BooleanField(_('staff status'), default=False,)
is_active = models.BooleanField(_('active'), default=False,)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email',]
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
I've also added in settings.py this piece of code:
AUTH_USER_MODEL = "myapp.User"
However, when I try to makemigrations for applying the changes, it appears this error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\base.py", line 399, in execute
output = self.handle(*args, **options)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\commands\makemigrations.py", line 105, in handle
loader.project_state(),
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\loader.py", line 338, in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\graph.py", line 280, in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\migration.py", line 88, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\operations\models.py", line 158, in state_forwards
apps = state.apps
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\state.py", line 162, in apps
return StateApps(self.real_apps, self.models)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\state.py", line 235, in __init__
raise ValueError(self._pending_models_error(pending_models))
ValueError: Unhandled pending operations for models:
myapp.user (referred to by fields: admin.LogEntry.user)
So I'm looking for info for possible solutions or causes for this error but can't figure out why it happens. May it have to be a problem with some previous migration? (if so, I have no clue of which nor why). I'd add more information if needed, but I'd really appreciate any clue of the cause of this error.
The custom user docs specifically warn against switching User model after you have already created migrations; there's too much dependency for that to work properly. You may need to delete your existing db and migrations and start from scratch.