Cannot add ManyToManyField objects in Django - django

I am unable to add ManyToManyField objects even after following the doc
models.py
class Label(models.Model):
...
name = models.CharField(blank=False, max_length=100)
class Template(models.Model):
...
labels = models.ManyToManyField(Label, blank=True, related_name="labels")
And then
>>> from content.models import Label, Template
>>> l1 = Label.objects.get_or_create(name='one') # saves in db
>>> l2 = Label.objects.get_or_create(name='two') # saves in db
>>> t1 = Template.objects.get(pk=1) # loads existing
>>> t1.labels.set([l1,l2]) # fails
throws this error
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1007, in set
self.add(*new_objs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items
'%s__in' % target_field_name: new_ids,
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1206, in build_filter
condition = lookup_class(lhs, value)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Label'
I am using Django 1.11 on Python 3.6.

You are using get_or_create which returns a tuple of (object, created), not just an object.
So l1 and l2 are not Label objects as you assume, but tuples. Passing this to the many-to-many manager will not work.
Change your code as follows:
from content.models import Label, Template
# Ignore the second item returned by get_or_create
l1, _ = Label.objects.get_or_create(name='one')
l2, _ = Label.objects.get_or_create(name='two') #
t1 = Template.objects.get(pk=1)
t1.labels.set([l1,l2])

Related

Django rest framework Serializer Save() problem

Hi there i am new ot django and django rest framework and i am having torouble when using serializers with PrimarayKeyTelatedFields() the code below is my code for my models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField(default=0)
class Book(models.Model):
name = models.CharField(max_length=40)
author = models.ForeignKey(to=Author, on_delete=models.CASCADE)
below is my serializer code
from rest_framework import serializers
from books.models import Book, Author
class BookSerializer(serializers.ModelSerializer):
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author_id']
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name', 'age']
and when i try to execute following commands in shell
>>from books.api.serializers import BookSerializer, AuthorSerializer
>> play1 = BookSerializer(data = { 'author_id':1 ,'name':'book1' })
>>play1.is_valid()
True
>>play1.save()
After executing above i got the huge error as i pasted below
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 981, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Book.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Book.objects.create()`. You may need to make the field read-only, or override the BookSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
you passed here an object instead of id..
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
you should pass an id like this
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.get(id=request.user.id))
Remember whatever you queried it should be an int value not str or object
Cause
The problem is caused by setting author_id with serializer.PrimaryKeyRelatedField
Explanation
Django will internally auto-create an attribute for related fields (ForeignKey, OneToOneField, ...) with the suffix _id appending to the declared field name. The data type of this field is a number. In this case, the author field in Book will have an attribute called author_id. The problem comes from serializer.PrimaryKeyRelatedField returning a model instance in the serializer's validated data, causing field author_id to be set with Author instance. Resulting in an error.
Solution
Rename author_id attribute to author.
class BookSerializer(serializers.ModelSerializer):
author = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author']

ValidationError - Django Q Query - is not a valid UUID

I am trying to get a value from the User Model, my requirement is that or condition should be in same query.
User.objects.get(
Q(premium_referral=form.cleaned_data.get('referral_code')) |
Q(id=form.cleaned_data.get('referral_code'))
)
But it gives an error:
ValidationError at /register
['“XUSB5” is not a valid UUID.']
The above query works perfect for id but not for premium_referral field. If I pass a UUID, it works, but if I pass 5 char premium_referral, then it fails.
Query also works perfectly when I separate them:
User.objects.get(premium_referral=form.cleaned_data.get('referral_code'))
User.objects.get(id=form.cleaned_data.get('referral_code'))
Below is the model:
class User(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True, blank=True, unique=True)
Traceback
Internal Server Error: /register
Traceback (most recent call last):
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "apps/accounts/views.py", line 31, in register
referrer = User.objects.get(
File "env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1265, in build_filter
return self._add_q(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1193, in build_lookup
lookup = lookup_class(lhs, rhs)
File "env/lib/python3.8/site-packages/django/db/models/lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "env/lib/python3.8/site-packages/django/db/models/lookups.py", line 77, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2418, in get_prep_value
return self.to_python(value)
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“XUSB5” is not a valid UUID.']
[19/Nov/2021 09:52:54] "POST /register HTTP/1.1" 500 154403
The reason this happens is because the id (or the premium_referral) is a UUIDField [Django-doc]. It thus does not make much sense to pass XUSB5 as code, since that is an invalid UUID).
What you can do is check if it can be converted to a UUID and thus filter with:
from uuid import UUID
query = form.cleaned_data.get('referral_code')
qobj = Q(premium_referral=query)
try:
qobj |= Q(id=UUID(query))
except ValueError:
pass
User.objects.get(
qobj
)

Djongo ArrayField 'Item' is not subscriptable

I have 2 models in my django project. DB is mongoDB and I use Djongo.
Here are the models:
class Item(models.Model):
item_id = models.IntegerField(primary_key=True)
item_name = models.CharField(max_length=30)
def __str__(self):
return f'<{self.item_name}>'
class Items(models.Model):
items_id = models.IntegerField(primary_key=True)
inventory = models.ArrayField(model_container=Item,)
neutral_item = models.EmbeddedField(model_container=Item,)
buffs = models.ArrayField(model_container=Item,)
def __str__(self):
return f'<{self.inventory}, {self.neutral_item}>'
When I do:
item = Item(item_name='Helmet')
items = Items(inventory=[item])
I am getting this TypeError:
'Item' object is not subscriptable
What is wrong?
Whole error message:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base
updated = self._save_table(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 924, in _do_insert
return manager._insert(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1390, in execute_sql
for sql, params in self.as_sql():
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1333, in as_sql
value_rows = [
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1275, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 215, in get_db_prep_save
return self.get_prep_value(value)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 222, in get_prep_value
processed_value = self._value_thru_fields('get_prep_value',
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 315, in _value_thru_fields
post_dict = super()._value_thru_fields(func_name,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 145, in _value_thru_fields
field_value = value[field.attname]
TypeError: 'Item' object is not subscriptable
According to the Djongo docs for ArrayField you should instantiate like this:
entry = Entry()
entry.authors = [{'name': 'John', 'email': 'john#mail.com'},
{'name': 'Paul', 'email': 'paul#mail.com'}]
entry.save()
So in your case, you would do this.
items = Items()
items.inventory = [
{'item_name': 'Helmet'}
]
items.save()

Bug in ModelMultipleChoiceField? Does not handle all data types

Using the following code, I get the sub sequent crash.
Here is a gist of the full django app: https://gist.github.com/thnee/8e7c6b22f350582efe57
Below are the important parts:
models.py
class Color(models.Model):
name = models.CharField(max_length=255)
class Shirt(models.Model):
name = models.CharField(max_length=255)
colors = models.ManyToManyField(Color)
forms.py
class ShirtForm(forms.ModelForm):
class Meta:
model = Shirt
using the form
def run_form(data):
form = ShirtForm(data)
if form.is_valid():
print 'success'
else:
print dict(form.errors)
# color id is integer (and 1 exists in database)
run_form({'name': 'foo', 'colors': [1,]})
# result: success
# color id is of type string
run_form({'name': 'foo', 'colors': ['asdf',]})
# result: {'colors': [u'"asdf" is not a valid value for a primary key.']}
# color id is of type list
run_form({'name': 'foo', 'colors': [['asdf'],]})
# expected result: {'colors': [u'["asdf"] is not a valid value for a primary key.']}
# actual result: TypeError: int() argument must be a string or a number, not 'list'
# color id is of type dict
run_form({'name': 'foo', 'colors': [{'asdf': 'qwer'},]})
# expected result: {'colors': [u'{"asdf": "qwer"} is not a valid value for a primary key.']}
# actual result: TypeError: int() argument must be a string or a number, not 'dict'
results in the following stack trace
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
return self.application(environ, start_response)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 206, in __call__
response = self.get_response(request)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 194, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mattiasll01/code/tests/model_multiple_choice_field_check_type/mmcfct/stuff/views.py", line 26, in test
run_form({'name': 'foo', 'colors': [['asdf'],]})
File "/home/mattiasll01/code/tests/model_multiple_choice_field_check_type/mmcfct/stuff/views.py", line 12, in run_form
if form.is_valid():
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/forms/forms.py", line 129, in is_valid
return self.is_bound and not bool(self.errors)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/forms/forms.py", line 121, in errors
self.full_clean()
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/forms/forms.py", line 273, in full_clean
self._clean_fields()
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/forms/forms.py", line 288, in _clean_fields
value = field.clean(value)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/forms/models.py", line 1186, in clean
self.queryset.filter(**{key: pk})
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/query.py", line 593, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/query.py", line 611, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1204, in add_q
clause = self._add_q(where_part, used_aliases)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1240, in _add_q
current_negated=current_negated)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1131, in build_filter
clause.add(constraint, AND)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/utils/tree.py", line 104, in add
data = self._prepare_data(data)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/sql/where.py", line 79, in _prepare_data
value = obj.prepare(lookup_type, value)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/sql/where.py", line 352, in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 369, in get_prep_lookup
return self.get_prep_value(value)
File "/home/mattiasll01/.virtualenvs/test/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 613, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'list'
Basically what I think would be better is to not only check for ValueError, but also TypeError here: https://github.com/django/django/blob/master/django/forms/models.py#L1218
I don't see anything weird in the results you get since your function is waiting a string or an int, so when you're passing a dict or a list, it does not make it.
I didn't test it at all but this could give you some ideas:
try:
run_form({'name': 'foo', 'colors': [['asdf'],]})
except TypeError:
# Don't make it crash here but handle errors yourself in form.errors
This was resolved in Django ticket 22808
https://code.djangoproject.com/ticket/22808

ValueError (invalid literal for int() with base 10) in django foreign keys

I'm working with a legacy database and am having some trouble connecting a foreign key in one table to a primary key in another table. I'd be most grateful for any help. Below are the models and my shell+ error. Thanks in advance.
Models:
class SectionMaster(models.Model):
. . .
crs_cde = models.ForeignKey('SectionSchedules', max_length=30, db_column=u'CRS_CDE', related_name='sm_crs_cde')
. . .
class SectionSchedules(models.Model):
. . .
crs_cde = models.CharField(max_length=30, db_column=u'CRS_CDE')
. . .
The error:
>>> q = SectionMaster.objects.filter(trm_cde=20).filter(yr_cde=2012)
>>> q2 = SectionSchedules.objects.filter(trm_cde=20).filter(yr_cde=2012)
>>> for course in q:
... for course2 in q2:
... if course.crs_cde == course2.crs_cde: ## also tried course.crs_cde_id
... print course.crs_cde, course.crs_title, course2.begin_dte
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
350, in __get__
rel_obj = qs.get(**params)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 358, in g
et
clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 624, in f
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 642, in _
filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1250,
in add_q
can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1185,
in add_filter
connector)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py", line 69, i
n add
value = obj.prepare(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py", line 320,
in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
972, in get_prep_lookup
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
310, in get_prep_lookup
return self.get_prep_value(value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: '0BJ 226 1
'
I expect you want to_field='crs_cde' on the ForeignKey to tell it to look at the value of the target table's crs_cde field, rather than the (integer) primary key.
Check your column crs_cde_id - it should be Int type in database. But seems like you have chars there.