Django/PIL: AttributeError: 'Image' object has no attribute 'read' - python

I'm testing example code validate image field (Django custom validation in model form for imagefield (max file size etc.)):
models.py
from django.db import models
from filer.fields.image import FilerImageField
class Event(models.Model):
# (...)
banner = FilerImageField(verbose_name='Banner')
admin.py
from django.contrib import admin
from django import forms
from PIL import Image
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = '__all__'
def clean_banner(self):
image = self.cleaned_data.get('banner', False)
if image:
img = Image.open(image)
img.load()
width, height = img.size
max_width = 879
max_height = 392
if width > max_width or width < max_width or height > max_height or height < max_height:
raise forms.ValidationError('Imagem está com dimensão incorreta: %s x %s pixels. Insira uma imagem com %s x %s pixels.'
%(width, height, max_width, max_height))
# Máx 3MB
if len(image) > (3 * 1024 * 1024):
raise forms.ValidationError('Arquivo de imagem muito grande (máximo 3MB).')
name_type, ext = image.content_type.split('/')
if not (name_type == 'image' and ext.lower() in ['png', 'jpg', 'jpeg']):
raise forms.ValidationError('Por favor, use imagem em formato JPG, JPEG ou PNG.')
else:
raise forms.ValidationError('Não foi possível ler a imagem carregada.')
return image
error when registering image not django-admin. Version: Pillow==4.3.0, Python==3.6
Traceback (most recent call last):
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\PIL\Image.py", line 2534, in open
fp.seek(0)
AttributeError: 'Image' object has no attribute 'seek'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\contrib\admin\options.py", line 551, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\contrib\admin\sites.py", line 224, in inner
return view(request, *args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\contrib\admin\options.py", line 1508, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\utils\decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\contrib\admin\options.py", line 1408, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\contrib\admin\options.py", line 1440, in _changeform_view
if form.is_valid():
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\forms\forms.py", line 183, in is_valid
return self.is_bound and not self.errors
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\forms\forms.py", line 175, in errors
self.full_clean()
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\forms\forms.py", line 384, in full_clean
self._clean_fields()
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\django\forms\forms.py", line 405, in _clean_fields
value = getattr(self, 'clean_%s' % name)()
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\integrafundaj\events\admin.py", line 19, in clean_banner
img = Image.open(image)
File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\PIL\Image.py", line 2536, in open
fp = io.BytesIO(fp.read())
AttributeError: 'Image' object has no attribute 'read'
I tried img = Image.open(image, mode='r') in function clean_banne, but it does not work. how to solve? the problem is in the python version?

According to Pillow documentation Python 3.6 is not yet supported. Please try another version of python.

Related

Django Error - AttributeError: 'CourseOverview' object has no attribute 'start_datetime_text'

I have been trying to get this theme working for Open edX (based on Django) and I am getting this error in supervisor logs -
AttributeError: 'CourseOverview' object has no attribute 'start_datetime_text'
The whole error is this -
May 14 11:43:36 ip-172-26-15-154 [service_variant=lms][django.request][env:sandbox] ERROR [ip-172-26-15-154 20450] [base.py:256] - Internal Server Error: /
Traceback (most recent call last):
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
return func(*args, **kwargs)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/edx/app/edxapp/edx-platform/common/djangoapps/util/cache.py", line 78, in wrapper
response = view_func(request, *args, **kwargs)
File "/edx/app/edxapp/edx-platform/lms/djangoapps/branding/views.py", line 94, in index
return student.views.index(request, user=request.user)
File "/edx/app/edxapp/edx-platform/common/djangoapps/student/views.py", line 221, in index
return render_to_response('index.html', context)
File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 198, in render_to_response
return HttpResponse(render_to_string(template_name, dictionary, context_instance, namespace, request), **kwargs)
File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 188, in render_to_string
return template.render_unicode(**context_dictionary)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/template.py", line 454, in render_unicode
as_unicode=True)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 829, in _render
**_kwargs_for_callable(callable_, data))
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 864, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 890, in _exec_template
callable_(context, *args, **kwargs)
File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/main.html.py", line 286, in render_body
__M_writer(filters.decode.utf8(self.body()))
File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/marvel-theme-eucalyptus/lms/templates/index.html.py", line 54, in render_body
runtime._include_file(context, (courses_list), _template_uri)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 752, in _include_file
callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs))
File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/marvel-theme-eucalyptus/lms/templates/courses_list.html.py", line 44, in render_body
runtime._include_file(context, u'course.html', _template_uri, course=course)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 752, in _include_file
callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs))
File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/marvel-theme-eucalyptus/lms/templates/course.html.py", line 60, in render_body
__M_writer(filters.html_escape(filters.decode.utf8(course.start_datetime_text())))
AttributeError: 'CourseOverview' object has no attribute 'start_datetime_text'
The file in question (the one that is giving the error - course.html.py) is here
https://pastebin.com/0S79hhDa
The start_datetime_text method was removed on november 30, 2016.
You should be using course.advertised_start. You can see the current version of the course.html template

Can't save image to django model

I try to resize image before save:
from PIL import Image
class UserAvatarUpdate(views.APIView):
serializer_class = UserSerializer
def patch(self, *args, **kwargs):
instance = ExtUser.objects.get(id=self.request.user.id)
instance.avatar = self.request.FILES['file']
size = 100,100
filename = instance.avatar.path
image = Image.open(filename)
image = image.resize(size,Image.ANTIALIAS)
instance.avatar = image
instance.save()
return Response(
UserSerializer(instance).data,
status=status.HTTP_200_OK
)
but I get the error below on save:
> Internal Server Error: /api/v1/update_user_avatar/ Traceback (most
> recent call last): File
> "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/core/handlers/base.py",
> line 149, in get_response
> response = self.process_exception_by_middleware(e, request) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/core/handlers/base.py",
> line 147, in get_response
> response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/views/decorators/csrf.py",
> line 58, in wrapped_view
> return view_func(*args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/views/generic/base.py",
> line 68, in view
> return self.dispatch(request, *args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/rest_framework/views.py",
> line 466, in dispatch
> response = self.handle_exception(exc) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/rest_framework/views.py",
> line 463, in dispatch
> response = handler(request, *args, **kwargs) File "/home/alexandr/sprutlabs_python/sprutlabs/posts/views.py", line 123,
> in patch
> instance.save() File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 74, in save
> super(AbstractBaseUser, self).save(*args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
> line 708, in save
> force_update=force_update, update_fields=update_fields) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
> line 736, in save_base
> updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File
> "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
> line 798, in _save_table
> for f in non_pks] File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
> line 798, in <listcomp>
> for f in non_pks] File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/fields/files.py", line 309, in pre_save
> if file and not file._committed: File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/PIL/Image.py",
> line 632, in __getattr__
> raise AttributeError(name) AttributeError: _committed
my model:
avatar = models.ImageField(
'Аватар',
blank=True,
null=True,
upload_to="user/avatar"
)
You can't directly assign a PIL image to an ImageField like so. You need a little workaround:
from io import BytesIO
from django.core.files.base import ContentFile
image = Image.open(filename)
image = image.resize(size,Image.ANTIALIAS)
image_io = BytesIO()
image.save(image_io, format='jpeg', quality=80) # you can change format and quality
# save to model
image_name = "my_image"
instance.avatar.save(image_name, ContentFile(image_io.getvalue()))

Python-social-auth pipeline returns TypeError when I'm trying to get access_token

I have custom pipeline in my django project. Following this example I'm trying to get access token (to get data from google plus) but it returns me TypeError: string indices must be integers.
Custom pipeline:
def user_details(strategy, details, response, user=None, *args, **kwargs):
....
if user:
if kwargs['is_new']:
if "google" in kwargs['backend'].redirect_uri:
...
try:
social = user.social_auth.get(provider='google-plus')
access_token = logger.warning(social.extra_data['access_token'])
....
except HTTPError:
pass
.....
Full traceback:
Traceback (most recent call last):
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/apps/django_app/utils.py", line 51, in wrapper
return func(request, backend, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/apps/django_app/views.py", line 28, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/actions.py", line 43, in do_complete
user = backend.complete(user=user, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/base.py", line 41, in complete
return self.auth_complete(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/google.py", line 158, in auth_complete
*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/oauth.py", line 398, in do_auth
return self.strategy.authenticate(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/strategies/django_strategy.py", line 96, in authenticate
return authenticate(*args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate
user = backend.authenticate(**credentials)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/base.py", line 82, in authenticate
return self.pipeline(pipeline, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/base.py", line 85, in pipeline
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
File "/home/linevich/.virtualenvs/tathros/lib/python3.4/site-packages/social/backends/base.py", line 112, in run_pipeline
result = func(*args, **out) or {}
File "/home/linevich/projects/tathros/proto/pipeline.py", line 54, in user_details
auth_token = social.extra_data['access_token']
TypeError: string indices must be integers
The solutuion was simple:
auth_token = json.loads(social.extra_data)['access_token']

AttributeError: type object 'YourClassHere' has no attribute 'rsplit'

I'm using django-rq, the django bindings for python-rq, to try generate a PDF asynchronously. The class TemplateProcesser initializes with two arguments and automatically generates the PDF in the __init__ function. This works fine synchronously, outside of django-rq, but with django-rq it fails with this error:
Error:
AttributeError: type object 'TemplateProcesser' has no attribute 'rsplit'
From this call:
django_rq.enqueue(TemplateProcesser, nail_order=serializer.object, user_photo=base64_image)
Any idea on how to correctly include the uninstantiated class in django-rq?
Class:
class TemplateProcesser(object):
def __init__(self, nail_order, user_photo, *args, **kwargs):
self.nail_order = nail_order
self.user_photo = user_photo
...
self.procces_template()
...
StackTrace:
Traceback (most recent call last):
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/worker.py", line 426, in perform_job
rv = job.perform()
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/job.py", line 386, in perform
self._result = self.func(*self.args, **self.kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/job.py", line 154, in func
return import_attribute(self.func_name)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/utils.py", line 168, in import_attribute
module_name, attribute = name.rsplit('.', 1)
AttributeError: type object 'TemplateProcesser' has no attribute 'rsplit'
Traceback after metaperture's answer:
Traceback (most recent call last):
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rest_framework/views.py", line 400, in dispatch
response = self.handle_exception(exc)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rest_framework/views.py", line 397, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/admin/dev/ncla-web/ncla/api/views.py", line 91, in post
django_rq.enqueue(self.template_processor_factory, **parameter_dict)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django_rq/queues.py", line 162, in enqueue
return get_queue().enqueue(func, *args, **kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/queue.py", line 213, in enqueue
description=description, depends_on=depends_on)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django_rq/queues.py", line 42, in enqueue_call
return self.original_enqueue_call(*args, **kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/django_rq/queues.py", line 37, in original_enqueue_call
return super(DjangoRQ, self).enqueue_call(*args, **kwargs)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/queue.py", line 176, in enqueue_call
return self.enqueue_job(job)
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/queue.py", line 232, in enqueue_job
job.save()
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/job.py", line 360, in save
connection.hmset(key, self.dump())
File "/Users/admin/dev/ncla-web/env/lib/python2.7/site-packages/rq/job.py", line 329, in dump
obj['data'] = dumps(self.job_tuple)
File "/Users/admin/dev/ncla-web/env/bin/../lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle BytesIO objects
Looks like python-rq expects a function as the first argument. I would try:
def template_processor_factory(*args, **kwargs):
return TemplateProcessor(*args, **kwargs)
django_rq.enqueue(template_processer_factory, nail_order=serializer.object,
user_photo=base64_image)

Django Admin crash when trying to delete an object

I have a problem where Django Admin (I run Django 1.3) crashes whenever I try to delete an object and the admin tries to display what child objects will be affected by the action. I'm able to delete the object fine in the terminal. This is the traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py", line 307, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/views/decorators/cache.py", line 79, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/sites.py", line 197, in inner
return view(request, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py", line 28, in _wrapper
return bound_func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py", line 24, in bound_func
return func(self, *args2, **kwargs2)
File "/usr/lib/python2.7/dist-packages/django/db/transaction.py", line 217, in inner
res = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py", line 1201, in delete_view
[obj], opts, request.user, self.admin_site, using)
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/util.py", line 104, in get_deleted_objects
to_delete = collector.nested(format_callback)
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/util.py", line 158, in nested
roots.extend(self._nested(root, seen, format_callback))
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/util.py", line 141, in _nested
children.extend(self._nested(child, seen, format_callback))
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/util.py", line 141, in _nested
children.extend(self._nested(child, seen, format_callback))
File "/usr/lib/python2.7/dist-packages/django/contrib/admin/util.py", line 136, in _nested
if obj in seen:
File "/test.py", line 371, in __eq__
return len(self.text) == len(other.text)
AttributeError: 'ChildB' object has no attribute 'text'
This is what my models look like:
class Parent(models.Model): pass
class ChildA(models.Model):
parent = models.ForeignKey(Parent)
text = models.CharField()
def __eq__(self, other):
return len(self.text) == len(other.text)
class ChildB(models.Model):
parent = models.ForeignKey(Parent)
counter = models.IntegerField()
Why does Django Admin try to compare ChildA and ChildB? I've fixed the issue by adding a check to make sure it's the right type before comparing text length but wondering if anyone else have had this problem and if there is an issue with my structure here. Even more strange is that this doesn't happen for all parent objects.
Thanks, Mattias
models are not correct
from django.db import models
class Parent(models.Model):
pass
class ChildA(models.Model):
parent = models.ForeignKey(Parent)
text = models.CharField()
def __eq__(self, other):
return len(self.text) == len(other.text)
class ChildB(models.Model):
parent = models.ForeignKey(Parent)
counter = models.IntegerField()
The function eq may lead this mistake, mark it and try again
def __eq__(self, other):
return len(self.text) == len(other.text)

Categories

Resources