I am new to Django & Python and have been following a tutorial, but I have an error that has me stumped.
I am attempting to build my django models / database.
When I attempt to run python manage.py syncdb I receive the following error in my command line prompt:
C:\Users\6233114\Django-Projects\GlobalX>python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
443, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 196,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 231,
in execute
self.validate()
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 266,
in validate
num_errors = get_validation_errors(s, app)
File "C:\Python27\lib\site-packages\django\core\management\validation.py", lin
e 30, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 158, in
get_app_errors
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 64, in
_populate
self.load_app(app_name, True)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 88, in
load_app
models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
__import__(name)
File "C:\Users\6233114\Django-Projects\GlobalX\app_data\models.py", line 15, i
n <module>
class LanguageCode(models.Model):
File "C:\Users\6233114\Django-Projects\GlobalX\app_data\models.py", line 27, i
n LanguageCode
languageDirectionID = models.ForeignKey(languageDirection, default=1, db_col
umn="languageDirectionID")
NameError: name 'languageDirection' is not defined
C:\Users\6233114\Django-Projects\GlobalX>
This is a cut down version of my models.py file (lines 1 - 29):
from django.db import models
from django.contrib.auth.models import User
class LanguageDirection(models.Model):
languageDirectionID = models.AutoField(primary_key=True, db_column="languageDirectionID")
languageDirectionDescription = models.CharField(max_length=20, db_column="languageDirectionDescription")
languageDirDescription = models.CharField(max_length=20, db_column="languageDirDescription")
textAlign = models.CharField(max_length=20, db_column="textAlign")
oppositeLanguageDirectionDescription = models.CharField(max_length=20, db_column="oppositeLanguageDirectionDescription")
oppositeLanguageDirDescription = models.CharField(max_length=20, db_column="oppositeLanguageDirDescription")
oppositeTextAlign = models.CharField(max_length=20, db_column="oppositeTextAlign")
class Meta:
db_table="languageDirection"
class LanguageCode(models.Model):
languagecodeID = models.AutoField(primary_key=True, db_column="languageCodeID")
languageCodeDescription = models.CharField(max_length=10, db_column="languageCodeDescription")
baseLanguageCode = models.CharField(max_length=10, db_column="baseLanguageCode")
languageNameEng = models.CharField(max_length=255, db_column="languageNameEng")
altLanguageNameEng = models.CharField(max_length=255, blank=True, null=True, db_column="altLanguageNameEng")
languageNameNative = models.CharField(max_length=255, db_column="languageNameNative")
altLanguageNameNative = models.CharField(max_length=255, blank=True, null=True, db_column="altLanguageNameNative")
iso639_1 = models.CharField(max_length=10, blank=True, null=True, db_column="iso639_1")
iso639_2T = models.CharField(max_length=10, db_column="iso639_2T")
iso639_2B = models.CharField(max_length=10, db_column="iso639_2B")
iso639_X = models.CharField(max_length=10, db_column="iso639_X")
languageDirectionID = models.ForeignKey(languageDirection, default=1, db_column="languageDirectionID")
class Meta:
db_table="languageCode"
The relationship between LanguageDirection & LangaugeCode is a one-to-many, where LanguageDirection.LanguageDirectionID (one) and LanguageCode.LanguageDirectionID (many).
Any suggestions as to what is causing this error and how I can fix this?
This is the meat of the error:
languageDirectionID = models.ForeignKey(languageDirection, default=1, db_col
umn="languageDirectionID")
NameError: name 'languageDirection' is not defined
The line should be:
languageDirectionID = models.ForeignKey(LanguageDirection, default=1, db_column="languageDirectionID")
Since the ForeignKey takes a class, or the name of a class in quotes such as "LanguageDirection".
NameError, for the future, means you're attempting to use a variable that is either not in scope, or does not exist.
Something that happened to me a few times is that when defining the models in Django, the Foreign key field relates to a model that´s defined further down in the same document.
This gives me no warnings in Pycharm 2.7 which I consider somewhat odd. Anyways, to solve this just put '' around the class name.
models.ForeignKey('SomeModel')
languageDirectionID = models.ForeignKey(languageDirection, default=1, db_column="languageDirectionID") should be languageDirectionID = models.ForeignKey(LanguageDirection, default=1, db_column="languageDirectionID"). The error refers to the issue that languageDirection, which should refer to the class name and not the DB table name for the foreign key target, is not capitalized correctly.
Related
I am trying to create a seeding script using Faker. In my models.ContentCategory, the parent_category has a recursive foreign key. However, I could not find a way to translate this into my faker script. I am really open to all kinds of helps!
here is my models.py:
class ContentCategory(models.Model):
name = models.CharField(blank=False, null=False, max_length=100)
description = models.CharField(blank=False, null=False, max_length=100)
parent_category = models.ForeignKey(
"self", on_delete=models.DO_NOTHING, null=True, blank=True, parent_link=True,
)
# down here should be fixed after creating the sections model
parent_section = models.ForeignKey(
Sections, on_delete=models.CASCADE, blank=True, null=True
)
def __str__(self):
return self.name
class Meta:
verbose_name = "content category"
verbose_name_plural = "Content Categories"
and here is the handler snippet:
#seeding Content Category
for _ in range(4):
name = fake.word(ext_word_list=None)
description = fake.sentence(nb_words=15, variable_nb_words=True, ext_word_list=None)
#creating ids and parent ids
cid = random.randint(1,4)
# creating key for Sections
ptid = random.randint(1,14)
ContentCategory.objects.create(
name=name, description=description, parent_category=cid, parent_section=ptid
)
check_content_categories = ContentCategory.objects.count().all()
here is the full error log:
python manage.py seed
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/myyagis/meethaq/be/be/api/management/commands/seed.py", line 104, in handle
ContentCategory.objects.create(
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/query.py", line 420, in create
obj = self.model(**kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/base.py", line 483, in __init__
_setattr(self, field.name, rel_obj)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 206, in __set__
raise ValueError(
ValueError: Cannot assign "1": "ContentCategory.parent_category" must be a "ContentCategory" instance.
Thank you in advance!
Solved:
In the model, the foreign key tables were already accepting blank=True, null=True, hence, I discarded these from the seeder script, it automatically filled the db with the null values.
Better solutions for non-nullable fields :
Model.objects.order_by('?').first() confirmed using.
recursive foreign key accepts the model's own name as the Model name.
example for the model UserCategory:
for _ in range(200):
category = UserCategory.objects.order_by('?').first()
email = fake.unique.ascii_free_email()
password = fake.unique.word(ext_word_list=None)
gender =fake.api_gender()
first_name = fake.unique.first_name()
last_name = fake.unique.last_name()
phone_number = fake.country_calling_code() + fake.phone_number()
birthday = fake.unique.date_of_birth()
I developed an API using Django Rest Framework.
I just changed my model in order to link my object to User object of Django by adding creationUser and updateUser :
class Document(models.Model):
name = models.CharField(max_length=100)
recipient = models.ForeignKey('Client', models.SET_NULL, null=True, verbose_name='Client')
provider = models.ForeignKey('Provider', models.SET_NULL, null=True, verbose_name='Provider')
type = models.CharField(max_length=50)
receptionDate = models.DateField()
fileName = models.CharField(max_length=200)
comment = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
status = models.CharField(max_length=5)
creationDate = models.DateTimeField(auto_now_add=True, editable=False)
updateDate = models.DateTimeField(auto_now=True)
creationUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='creationUser') # New Line
updateUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='updateUser') # New Live
def __str__(self):
return "Id : {0} | Nom : {1} | Fournisseur : {2} | Type : {3} | Date de reception : {4}".format(self.id, self.name, self.provider, self.type, self.receptionDate)
Then I execute :
pipenv run python manage.py makemigrations
pipenv run python manage.py migrate
First line works, but second line provides :
Operations to perform:
Apply all migrations: admin, api, auth, contenttypes, inbox, sessions
Running migrations:
Applying api.0027_auto_20180721_0106...Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 335, in execute
output = self.handle(*args, **options)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
fake_initial=fake_initial,
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
field,
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 407, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 152, in column_sql
default_value = self.effective_default(field)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\backends\base\schema.py", line 224, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\related.py", line 936, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 767, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 939, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'
I can't understand the Reason. I tried to remove creationUser and updateUser and run the two commands again but the issue keep happenning.
As requested by Bernard Parah, here is the api.0027_auto_20180721_0106.py file :
# Generated by Django 2.0.3 on 2018-07-20 23:06
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0026_case_description'),
]
operations = [
migrations.AddField(
model_name='document',
name='creationUser',
field=models.ForeignKey(default=django.contrib.auth.models.User, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='creationUser', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='document',
name='updateUser',
field=models.ForeignKey(default=django.contrib.auth.models.User, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='updateUser', to=settings.AUTH_USER_MODEL),
),
]
There's something wrong in your migration file.
field=models.ForeignKey(default=django.contrib.auth.models.User, ...
There should be no default argument there, and User is not a proper value for default in any case. I don't know what might have happened, since the default are not in your Document model. Try removing both default=django.contrib.auth.models.User, from the migration file and run manage.py migrate again.
You can also try to just delete the migration file and rebuild it with makemigrations
I have a Django app that has CustomUser. My model looks something like
class CustomUser(AbstractBaseUser):
def get_short_name(self):
pass
def get_full_name(self):
pass
firstName = models.CharField(max_length=300)
middleName = models.CharField(max_length=300, blank=True)
lastName = models.CharField(max_length=300, blank=True)
username = models.CharField(unique=True, max_length=50)
businessName = models.CharField(max_length=500, default=None)
mobileNumber = models.CharField(max_length=20)
contactNumber = models.CharField(max_length=20)
addressLine1 = models.CharField(max_length=300)
addressLine2 = models.CharField(max_length=300)
city = models.CharField(max_length=300)
state = models.CharField(max_length=300)
role = models.CharField(max_length=20)
email_id = models.CharField(max_length=300, unique=True)
aadharNumber = models.BigIntegerField(default=0)
panNumber = models.CharField(max_length=20, default=None)
registrationDate = models.BigIntegerField(default=0)
bankDetail = models.ManyToManyField('BankDetail', related_name="bankDetail")
dateCreated = models.DateTimeField(auto_now_add=True)
dateModified = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email_id'
REQUIRED_FIELDS = ['username']
I was following the example in this blog https://afropolymath.svbtle.com/authentication-using-django-rest-framework to implement User authentication.
I get the following error when I run makemigrations
I did look at a few solutions on StackOverflow but those don't seem to solve my problem.
Django error message "Add a related_name argument to the definition"
AlterField on auto generated _ptr field in migration causes FieldError
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 177, in handle
migration_name=self.migration_name,
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 47, in changes
changes = self._detect_changes(convert_apps, graph)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 133, in _detect_changes
self.old_apps = self.from_state.concrete_apps
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 222, in concrete_apps
self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 288, in __init__
self.render_multiple(list(models.values()) + self.real_models)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 323, in render_multiple
model.render(self)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 626, in render
body,
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 259, in __new__
base.__name__,
django.core.exceptions.FieldError: Auto-generated field 'user_ptr' in class 'CustomUser' for parent_link to base class 'User' clashes with declared field of the same name.
customer ID<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x106341a58>
What do I need to do to get rid of this error and proceed with a successful migration?
Delete your migrations .
Then run makemigrations command.
I am working on a Django web app with south for db migration. I am quite new to south, and django as well. I tried using south with the official tutorials, however it failed with an exception: AttributeError: 'Options' object has no attribute 'index_together'.
I run the south command like this:
python manage.py schemamigration southtut --initial
The southtut models is this:
class Knight(models.Model):
name = models.CharField(max_length=100)
of_the_round_table = models.BooleanField()
My project models is this:
class Author(models.Model):
name = models.CharField(max_length=64)
authorId = models.CharField(max_length=32)
def __unicode__(self):
return self.name
class Meta:
db_table="Author"
class Video(models.Model):
videoId = models.CharField(max_length=32)
videoUrl = models.URLField(max_length=200)
author = models.ForeignKey(Author, null=True, related_name="videos", on_delete=models.SET_NULL)
class Meta:
db_table="Video"
class User(models.Model):
token = models.CharField(max_length=50, null=True)
favs = models.ManyToManyField(Video, related_name="fans", db_table="VideoUserR")
class Meta:
db_table = "User"
The whole error message I got is as below:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/management/commands/schemamigration.py", line 151, in handle
for action_name, params in change_source.get_changes():
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/changes.py", line 460, in get_changes
model_defs = freeze_apps([self.migrations.app_label()])
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/freezer.py", line 37, in freeze_apps
model_defs[model_key(model)] = prep_for_freeze(model)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/freezer.py", line 78, in prep_for_freeze
fields['Meta'] = remove_useless_meta(modelsinspector.get_model_meta(model))
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/modelsinspector.py", line 441, in get_model_meta
meta_def[kwd] = get_value(model._meta, defn)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/modelsinspector.py", line 258, in get_value
value = get_attribute(field, attrname)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/utils/__init__.py", line 38, in get_attribute
value = getattr(value, part)
AttributeError: 'Options' object has no attribute 'index_together'
Thanks
It's bug in south 0.8. Just update to 0.8.1 or newer and all be good.
It looks like this is because you are trying to use index_together option in Meta section of your model. But this option is available only for django 1.5+ and i guess that you run it on a less recent version of django.
I updated my django to 1.5.1, and this error disappeared. I have no idea how the 'index_together' come out, but since it is available in django 1.5.1, it get what it needs.
Hi I'm attempting to write some unittests for my django web application but I'm running into some database problems when trying to run my tests. I'm using Factory Boy in some places in order to create instances for the tests (https://github.com/dnerdy/factory_boy is the repo) but I'm running into some problems when I attempt to run my tests. I'm getting database errors such as: no such column when I try to run my tests and table already exits errors when I try to run ./manage.py syncdb (I'll include the actual errors below). I'm using the default sqlite3 database settings for testing so the test DB is created to run the tests then destroyed afterward automatically.
Here are the pertinent sections of my settings.py file
if 'test' in sys.argv or 'jenkins' in sys.argv:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test_ndptc'
}
}
Here is the model that is throwing the error.
class CourseManager(models.Manager):
def get_query_set(self):
return super(CourseManager, self).get_query_set().order_by('CourseName')
class Course(models.Model):
"""
"""
CourseName = models.CharField(max_length=80)
ShortName = models.CharField(max_length=50)
CourseNumber = models.CharField(max_length=50)
TrainingProvider = models.ForeignKey(TrainingProvider)
TrainingType = models.ForeignKey(TrainingType)
CourseType = models.ForeignKey(CourseType)
ModuleCount = models.IntegerField()
ContactHours = models.CharField(max_length=5)
Certified = models.BooleanField()
Description = models.TextField(null=True, blank=True)
TargetAudience = models.TextField(null=True, blank=True)
Prerequisites = models.TextField(null=True, blank=True)
Requirements = models.TextField(null=True, blank=True)
Icon2d = models.FileField(upload_to='icons/', null=True, blank=True)
Icon3d = models.FileField(upload_to='icons/', null=True, blank=True)
Status = models.IntegerField(null=True)
UpdateUser = models.ForeignKey(User, null=True)
UpdateDate = models.DateField(null=True)
Featured = models.BooleanField(verbose_name='is featured?')
objects = CourseManager()
Here is the factory where the error occurs.
class TestFactory(factory.Factory):
FACTORY_FOR = Test
Course = random.choice(Course.objects.all())
EffectiveDate = '01/01/2012'
Type = random.choice(TestType.objects.all())
Label = 'test_label'
Status = 1
UpdateUser = factory.LazyAttribute(lambda a: UserFactory())
UpdateDate = '01/01/2012'
And finally here is the error that occurs when I run ./manage.py test
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1- py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
failures = test_runner.run_tests(test_labels)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
suite = self.build_suite(test_labels, extra_tests)
File "/home/brandon/course-management/Testing/runner.py", line 17, in build_suite
suite = unittest.defaultTestLoader.loadTestsFromNames(test_labels)
File "/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
File "/home/brandon/course-management/Testing/admin_tests.py", line 5, in <module>
from Testing.Factories.course_factory import *
File "/home/brandon/course-management/Testing/Factories/course_factory.py", line 19, in <module>
class TestFactory(factory.Factory):
File "/home/brandon/course-management/Testing/Factories/course_factory.py", line 22, in TestFactory
Course = random.choice(Course.objects.all())
File "/usr/lib/python2.7/random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 234, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.DatabaseError: no such column: Course_course.ShortName
I think that random.choice is running on a empty list. I think you could use a lazy attribute, e.g.
#factory.lazy_attribute
def course(a):
""" Creates a course if none exist
"""
if Course.objects.count() == 0:
course = CourseFactory()
return course
else:
return random.choice(Course.objects.all())