Django fails when saving a serializer with foreign key references - python

So I had a model with one foreign key reference that was working really well for a few weeks. I ended up having to add another foreign key reference to the model and now I'm not able to save any records using a serializer. I should mention I'm using Django 2.1.
Here's the model I'm using (some fields removed for simplicity):
class Finding(models.Model):
finding_id = models.IntegerField(null=False, blank=False, primary_key=True, db_index=True)
name = models.CharField(null=True, blank=True, max_length=255)
web_app = models.ForeignKey(WebApplication, on_delete=models.CASCADE)
q_id = models.ForeignKey(StagingQkb, on_delete=models.CASCADE)
The new FK is the q_id field. This was just a plain int before. I've actually blown away the old table and the new one is still totally empty so I know it's not a problem with the existing data (the tables with the foreign keys are still intact). When saving Findings before, I would just give the PK of the WebApplication object for 'web_app'. As far as I can tell this is still working. The 'q_id' field, when inserted the same way, complains that it needs an int/string/bytes instead of a StagingQkb object. Well, I'm not giving it a StagingQkb object so what gives!
Here's the serializer:
class FindingSerializer(serializers.ModelSerializer):
class Meta:
model = Finding
fields = '__all__'
The data I'm feeding to the serializer looks like this:
data = {'finding_id': 5514989,
'name': 'Sample-Name',
'q_id': 12345,
'web_app': 67890}
When I insert the data into the serializer I'm doing the following:
>>> fs = FindingSerializer(data=data)
>>> fs.is_valid()
True
>>> fs.save()
The error I'm getting after running the above code looks like this:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 959, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Finding.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Finding.objects.create()`. You may need to make the field read-only, or override the FindingSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 940, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "/home/dpz3w0q/AutonomousPrimeD/autonomousprimed/Finding/models.py", line 83, in save
q_id=self.q_id)
File "/home/dpz3w0q/AutonomousPrimeD/autonomousprimed/Finding/models.py", line 173, in evaluate
if ScoreMatrix.objects.filter(q_id=q_id).count() > 0:
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 844, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1263, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
split_subq=split_subq,
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1225, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1096, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1807, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'StagingQkb'
I'm completely stuck here. I haven't changed the way I'm passing data to the serializer, so I really can't tell what I've done wrong. If anyone is able to help me work through this I'd really appreciate it!

Thanks to #WillKeeling I realized that I had a reference to Finding.q_id in my save() method that I forgot to update after making the FK changes. The PK of the foreign table is qkb_id, so I changed the reference to Finding.q_id.qkb_id and I was able to save the model.

Related

Models and ModelForms: needs to have a value for field "id" before this many-to-many relationship can be used

I'm using a Django Model with some many-to-many fields. I'm also using a ModelForm to generate the associated form. It is my understanding that, provided nothing else is overridden, Django should be able to handle many-to-many fields being saved in the ModelForm?
For me, attempting to do this is causing this error:
Internal Server Error: /cameramodel/create/
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.8/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.8/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.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 141, in post
if form.is_valid():
File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 180, in errors
self.full_clean()
File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 383, in full_clean
self._post_clean()
File "/usr/local/lib/python3.8/site-packages/django/forms/models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 1188, in full_clean
self.clean()
File "./schema/models.py", line 1439, in clean
if self.metering_modes is True:
File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 527, in __get__
return self.related_manager_cls(instance)
File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 838, in __init__
raise ValueError('"%r" needs to have a value for field "%s" before '
ValueError: "<CameraModel: Canon Canonflex R2000>" needs to have a value for field "id" before this many-to-many relationship can be used.
So I checked out the docs and it seems like I need to override the save method in the ModelForm. So I did this:
class CameraModelForm(ModelForm):
class Meta:
model = CameraModel
fields = '__all__'
def save(self, commit=True):
form = super(CameraModelForm, self).save(commit=False)
if commit:
form.save(commit=False)
form.save_m2m()
return form
and instead I'm getting a different error:
TypeError at /cameramodel/create/
save() got an unexpected keyword argument 'commit'
Request Method: POST
Request URL: http://localhost:8000/cameramodel/create/
Django Version: 2.2.12
Exception Type: TypeError
Exception Value:
save() got an unexpected keyword argument 'commit'
Exception Location: /home/jonathan/git/camerahub/schema/models.py in save, line 1397
and models.py:1397 is actually an overridden Model save to add a slug field:
class CameraModel(models.Model):
# other stuff here
def save(self, *args, **kwargs):
if not self.slug:
custom_slugify_unique = UniqueSlugify(
unique_check=cameramodel_check, to_lower=True)
self.slug = custom_slugify_unique("{} {} {}".format(
self.manufacturer.name, self.model, str(self.disambiguation or '')))
super().save(*args, **kwargs)
For what it's worth, I am using many-to-many fields in some other models and I'm not seeing a problem with them. I'm a Python/Django beginner though and I'm pretty stuck on this one because simply following the advice on a million other posts like this one hasn't helped me. Grateful for any advice or code snippets anyone can offer.
If anyone needs more context, the whole project is open source and this branch is available here: https://github.com/djjudas21/camerahub/tree/278c_m2m_error
If you override, the save method, it means you want to make some checks/changes before saving your form. I would instead do:
def save(self):
form = super(CameraModelForm, self).save(commit=False)
if ...: # some condition on form values
form.save() # remove the commit here
form.save_m2m()
return form

Django REST framework - MultiSelectField - TypeError: Object of type 'set' is not JSON serializable

I'm trying to make a multi-choice rest api with Django REST framework and django-multiselectfield.
Currently inside the model I have:
ANIMAL = (
('dog', 'Dog'),
('cat', 'Cat'),
)
class MyForm(models.Model):
...
animals = MultiSelectField(choices=ANIMAL)
and in my serializer I have:
class MyFormSerializer(serializers.ModelSerializer):
class Meta:
model = MyForm
fields = (..., 'animals')
animals = fields.MultipleChoiceField(choices=ANIMAL)
When I'm trying to POST into the api using this kind of body:
{
...
"animals": ["cat"],
...
}
I get an error: TypeError: Object of type 'set' is not JSON serializable
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "c:\mysite\myserver\myform\views.py", line 15, in angels_add
return JsonResponse(serializer.data, status=201)
File "C:\Python36\lib\site-packages\django\http\response.py", line 558, in __init__
data = json.dumps(data, cls=encoder, **json_dumps_params)
File "C:\Python36\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python36\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python36\lib\site-packages\django\core\serializers\json.py", line 104, in default
return super().default(o)
File "C:\Python36\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'set' is not JSON serializable
Though, the form is submitted and I can see the entire data in the admin panel succesfully (?).
I'm using the following versions:
Django==2.2.1
djangorestframework==3.9.3
django-multiselectfield==0.1.8
any idea why I get this exception?
also, I can switch from multiselectfield to another technology if something else would work and will allow me to add multiple choice fields which I can filter later from the admin panel
class MyFormAdmin(admin.ModelAdmin):
list_filter = (
'animals',
...
)
I've read about ArrayField, but I'm not happy with a solution that fit only one kind of db (postgres) as I might use another.
Thanks in advance,
Etay.
From the source code, the to_representation() method of MultipleChoiceField returns data as set
Create a custom MultipleChoiceField class and use it in your serializer
class CustomMultipleChoiceField(fields.MultipleChoiceField):
def to_representation(self, value):
return list(super().to_representation(value))
class MyFormSerializer(serializers.ModelSerializer):
class Meta:
model = MyForm
fields = (..., 'animals')
animals = CustomMultipleChoiceField(choices=ANIMAL)
JPG's solution might work in some cases, but is not really rugged. (also depends on your use case)
A more low level way of solving this, is by extending the JSONEncoder or even better DjangoJSONEncoder (which is already extended) and using it. This way, you only have to implement it ones.
class CustomJSONEncoder(DjangoJSONEncoder):
"""
Custom encoder that also supports `set`, since we require this for
saving the `MultipleChoiceField`.
"""
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return super().default(obj)

Failed to retrieve list of Django objects with models.Manager

I have the following structure scenario in my models.py :
from django.db import models
class SensorManager(models.Manager):
def create_sensor(self,numero,pinoFisico):
sensor = self.create(numero = numero,
pinoFisico = pinoFisico,
ativo = False)
return sensor
class Sensor(models.Model):
numero = models.IntegerField()
pinoFisico = models.IntegerField()
ativo = models.BooleanField()
dataUltimoReconhecimento = models.DateTimeField()
situacao = None
moduloSensor = None
#Manager
objects = SensorManager()
def __init__(self):
self.moduloSensor = ModuloSensor()
and, in views.py file, i have this:
def formSensores(request):
sensores = Sensor.objects.all()
print sensores
return render(request,"speedapp/monitoraSensores.html",{"sensores": sensores})
When I try to use objects in
print sensores
i get the following stack:
[17/Apr/2017 00:38:09] "GET /speedapp/ HTTP/1.1" 200 3649
Internal Server Error: /speedapp/sensores/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Documents/speed_project/speed/speedapp/views.py", line 39, in formSensores
print sensores
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 234, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 69, in __iter__
obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in from_db
new = cls(*values)
TypeError: __init__() takes exactly 1 argument (6 given)
[17/Apr/2017 00:38:11] "GET /speedapp/sensores/ HTTP/1.1" 500 15557
As the stack, it seems to be a problem at the moment of building the Sensor object by the SensorManager method in the __init__() method in class from_db, where N arguments were expected ... this problem is related to the my Custom Manager SensorManager?
P.S:
This error does not happens for other objects that are also used with the "all()" method through models.Manager, only for this Sensor class
Only happen when i try "use" instance of list objects, get with all() method, for example: print the value of it
I found this and this related questions in my search, But I could not solve my problem with them
So here's the high level answer. The problem is that you were overriding the __init__ method on the model. You really, really should try to avoid that. Here's some documentation on other options; read the big green note: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model
Here's an excerpt:
You may be tempted to customize the model by overriding the __init__ method...Rather than overriding __init__, try using one of these approaches
1. Add a classmethod on the model class
2. Add a method on a custom manager (usually preferred)
If you absolutely need to override __init__, then don't forget to call super() pass the values down, and let Django do its stuff first.

Django: model OneToOneField with User can't add default value

I have an model and I want to add an OneToOneField to hold the creator of an object:
models.py
creator = models.OneToOneField(User, blank=True,
default=User.objects.filter(
username="antoni4040"))
I already have a database with items and just want the default value to be the admin user, which has the username "antoni4040". When I try to migrate without the default field it asks for a default value, so I can't get away with it. But here's what I get when running makemigrations:
Migrations for 'jokes_app':
0008_joke_creator.py:
- Add field creator to joke
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/commands/makemigrations.py", line 150, in handle
self.write_migration_files(changes)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/commands/makemigrations.py", line 178, in write_migration_files
migration_string = writer.as_string()
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 167, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 124, in serialize
_write(arg_name, arg_value)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 88, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 433, in serialize
return cls.serialize_deconstructed(path, args, kwargs)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 318, in serialize_deconstructed
arg_string, arg_imports = cls.serialize(arg)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 517, in serialize
item_string, item_imports = cls.serialize(item)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/writer.py", line 540, in serialize
"topics/migrations/#migration-serializing" % (value, get_docs_version())
ValueError: Cannot serialize: <User: antoni4040>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/1.9/topics/migrations/#migration-serializing
What am I doing wrong?
You are using the queryset User.objects.filter(username="antoni4040"). To get a model instance, you would use User.objects.get(username="antoni4040").
However, you shouldn't use a a model instance for as the default in the model field. There's no error handling if the user does not exist in the database. In fact, if models.py is loaded before you run the initial migrations, then the User table won't even exist so the query will give an error.
The logic to set the default user should go in the view (or Django admin) instead of the models file.
In the admin, you could define a custom form that sets the initial value for the creator field.
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
try:
user = User.objects.get(username="antoni4040")
kwargs['initial']['creator'] = user
except MyModel.DoesNotExist:
pass
super(MyModelForm, self).__init__(*args, **kwargs)
Then use that model form in your admin.
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
...
If you really wanted to do this you can open up a shell and get the id for that User, then set the default to that.
The problem is, why would you do that? The first time you add a model it will use the default correctly. The second time you try to do that, it will fail because it's one to one, not many to one, so it will fail.

EncodeError: 'QuerySet' object has no attribute '_prefetch_related_lookups'

I recently updated my version of django from 1.2.5 to 1.7. Once done, all new transactions on my app were working as expected. However whenever I try to access a pickled object, I get the error
EncodeError: 'QuerySet' object has no attribute '_prefetch_related_lookups'
Here is the error thrown
'QuerySet' object has no attribute '_prefetch_related_lookups'
Traceback (most recent call last):
File "/foo/bar/gateway/baseGateway.py", line 108, in queueMessage
eng.processMessage(msgRow)
File "/foo/bar/engine/processor.py", line 101, in processMessage
tasks.deliverMessage.apply_async(args=[foo, bar], queue='message-deliver')
File "/opt/bitnami/python/lib/python2.7/site-packages/celery/app/task.py", line 555, in apply_async
**dict(self._get_exec_options(), **options)
File "/opt/bitnami/python/lib/python2.7/site-packages/celery/app/base.py", line 353, in send_task
reply_to=reply_to or self.oid, **options
File "/opt/bitnami/python/lib/python2.7/site-packages/celery/app/amqp.py", line 305, in publish_task
**kwargs
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/messaging.py", line 161, in publish
compression, headers)
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/messaging.py", line 237, in _prepare
body) = dumps(body, serializer=serializer)
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/serialization.py", line 164, in dumps
payload = encoder(data)
File "/opt/bitnami/python/lib/python2.7/contextlib.py", line 35, in __exit__
self.gen.throw(type, value, traceback)
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/serialization.py", line 59, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/serialization.py", line 55, in _reraise_errors
yield
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/serialization.py", line 164, in dumps
payload = encoder(data)
File "/opt/bitnami/python/lib/python2.7/site-packages/kombu/serialization.py", line 356, in pickle_dumps
return dumper(obj, protocol=pickle_protocol)
File "/opt/bitnami/python/lib/python2.7/site-packages/django/db/models/query.py", line 113, in __reduce__
return super(QuerySet, self).__reduce__()
File "/opt/bitnami/python/lib/python2.7/copy_reg.py", line 84, in _reduce_ex
dict = getstate()
File "/opt/bitnami/python/lib/python2.7/site-packages/django/db/models/query.py", line 91, in __getstate__
self._fetch_all()
File "/opt/bitnami/python/lib/python2.7/site-packages/django/db/models/query.py", line 967, in _fetch_all
if self._prefetch_related_lookups and not self._prefetch_done:
EncodeError: 'QuerySet' object has no attribute '_prefetch_related_lookups'
Looking at some of the solutions offered online and by django here and here, I cleared the sessions table in django to no avail.The error still persists. I use memcache in my application too and i cleared that. I also use celery.
Anyone know how to fix this?
I was seeing a related issue when trying to change a queryset on a model form within a view. The error was:
'NoneType' object has no attribute '_prefetch_related_lookups'
forms.py
class S1Form(forms.ModelForm):
library = forms.ModelChoiceField(
queryset = Library.objects.all(),
to_field_name = 'title',
required = True,
widget = forms.Select(
attrs = {
'class': 'custom-select'}
),
disabled = False,
empty_label = 'Select a library'
)
views.py
class FilteredSpectraSearchListView(SingleTableMixin, FilterView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['sform'] = S1Form()
context['sform'].fields['library'].queryset = None
if <something>:
context['sform'].fields['library'].queryset = <...>
elif <something-else>:
context['sform'].fields['library'].queryset = <...>
return context
The goal was to have an empty queryset initially which is later changed based on a few conditional statments. The problem was that the conditional "<something>" was not firing and None remained the queryset. The solution was simply to provide an empty queryset rather than None for this case:
...
context['sform'].fields['library'].queryset = Library.objects.none()
if <something>:
context['sform'].fields['library'].queryset = <...>
elif <something-else>:
context['sform'].fields['library'].queryset = <...>
...
Googling giving us a results
resetting sessions app fixed the issue (at least for the moment...)
https://code.djangoproject.com/ticket/18674
The problem is the Sessions, I had to delete them all for it to work. Addtionally I changed the settings SECRET_KEY so all sessions don’t validate.
http://jj.isgeek.net/2013/04/django-queryset-object-has-no-attribute-_prefetch_related_lookups/
You have some serialized data from Django < 1.4, and Kombu tries to deserialize it in your current Django version.
I don't know where Kombu saves its serialized data, but that's where you should look. You should either delete the stale data, or if you need to keep the data, manually change it to match your current Django version.

Categories

Resources