Posts Tagged ‘python’

ValueError in Django migration

Sunday, May 15th, 2016

I’ve recently started developing in Python+Django again for a personal site that I’m working on and for far too long today I’ve been pulling my hair out when trying to write what should be a fairly simple migration using migrations.RunPython() to generate a default value to assign to a new OneToOneField column.

The rather confusing error message that I was receiving is:

ValueError: Cannot assign "<User: blah>": "Profile.account" must be a "User" instance.

This seems to be the same problem described at http://stackoverflow.com/questions/29700001/valueerror-cannot-assign-user-issue-on-my-onetoonefield-relationship, but nothing mentioned in that post worked.

I was hopeful when I came across https://code.djangoproject.com/ticket/24282 that this was a known issue, but alas whilst similar it’s not exactly the same problem and that bug was closed over a year ago. Back to square one!

What was particularly confusing was that the same code seemed to work as expected when run in the Django shell:

from foo.models import Profile, Article
from django.contrib.auth.models import User
first_superuser = User.objects.all().filter(is_superuser=True).first()
default_profile = Profile(account=first_superuser, biography="")
default_profile.save()

After a lot of fiddling, I eventually realised that the way which I was importing the User model from the built in Django auth system was wrong for a migration and so I replaced:

from django.contrib.auth.models import User

with:

User = apps.get_model('auth', 'user')

And now the migration finally works as expected. 🙂

Python setuptools and get_python_version is not defined

Sunday, September 12th, 2010

If you run into the below error when using setuptools (setup.py), then it’s quite possible that you’re using an outdated version of Python’s setuptools. In particular, the python-setuptools package in the CentOS yum repository is too old.

Traceback (most recent call last):
File “setup.py”, line 19, in ?
setup(**metadata)
File “/usr/lib64/python2.4/distutils/core.py”, line 149, in setup
dist.run_commands()
File “/usr/lib64/python2.4/distutils/dist.py”, line 946, in run_commands
self.run_command(cmd)
File “/usr/lib64/python2.4/distutils/dist.py”, line 966, in run_command
cmd_obj.run()
File “/usr/lib/python2.4/site-packages/setuptools/command/bdist_rpm.py”, line 28, in run
_bdist_rpm.run(self)
File “/usr/lib64/python2.4/distutils/command/bdist_rpm.py”, line 377, in run
self.move_file(rpm, self.dist_dir)
File “/usr/lib/python2.4/site-packages/setuptools/command/bdist_rpm.py”, line 20, in move_file
getattr(self.distribution,’dist_files’,[]).append(
NameError: global name ‘get_python_version’ is not defined

Luckily, this is quite easy to fix; simply remove the RPM and download the latest version from http://pypi.python.org/pypi/setuptools then just run it with “sh” as if it was a normal shell script.