Cannot Create Superuser After Add Custom User Model - python

I create CustomUser class that extends AbstractUser, and add a ForeignKey field that reference to City Model
class City(models.Model):
created_dt = models.DateTimeField("Created Time", auto_now_add=True)
code = models.CharField(max_length=64, unique=True)
name = models.CharField(max_length=64)
class CustomUser(AbstractUser):
city = models.ForeignKey(City)
REQUIRED_FIELDS = ['city']
I add the CustomUser to setting:
AUTH_USER_MODEL = "myapp.CustomUser"
When I tried to syncdb, it prompted me to create super user, when I fill in the city, I got this error:
City: 1
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 116, in handle
user_data[field_name] = field.clean(raw_value, None)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 255, in clean
self.validate(value, model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1201, in validate
using = router.db_for_read(model_instance.__class__, instance=model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/utils.py", line 250, in _route_db
return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'NoneType' object has no attribute '_state'
can someone explain to me why ?
I'm still a newbie in django, thanks

You can't set a required field to be a foreign key according to the docs. There's a ticket open with something similar to what you're encountering. I'd suggest subclassing CustomUserManager and override the create_superuser method on it, then use it for the objects manager on your CustomUser model.

Related

Django Error (Attribute): 'CharField' object has no attribute 'is_related'

I am trying to make a description to every user, in my new project. But i get an error when i try to makemigrations. I do not know how to fix it.
I have tried different things but nothing worked, my coding is maybe very bad, but i am also new to python and django.
The Error:
C:\Users\bruger\Dropbox\min-login-web\web_login>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 143, in handle
loader.project_state(),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\loader.py", line 322, in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\graph.py", line 378, in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 87, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\models.py", line 85, in state_forwards
list(self.managers),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\state.py", line 377, in __init__
if field.is_relation and hasattr(field.related_model, '_meta'):
AttributeError: 'CharField' object has no attribute 'is_relation'
My Models file:
from django import forms
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
class Desc(models.Model):
description = forms.CharField(widget = forms.Textarea, max_length = 250, required=False)
def __str__(self):
return f'{self.user.username} Desc'
I Hope somebody can help me, because this is really getting on my nerves.
You mixed forms and models. A model does not specify a (HTML) form, it specifies how the database should store data, so you need to use a models.CharField:
class Desc(models.Model):
description = models.CharField(max_length=250)
Such CharField has no widget assigned to it, this is something you should handle at the form level.
You probably will need to make migrations, since up to this point, there was no description field in your Desc model.
I agree to some extent that it is confusing that the forms have frequently a field with the same name (well those typically are the default form fields for the model field with the same name). The idea is however that model fields specify the columns in a database, whereas form fields specify text boxes, check boxes, etc. in a (HTML) form.

"auth_user does not exist" when doing unit testing in django

I've been trying to solve this error for a week now and I can't seem to figure out how to fix this error. No one else who is using this repository is having the same problem as I am (I am up to date with the origin), so it has to be some sort of local issue, but I can't figure out what it would be.
This happens everytime I try to run the django unit tests that we have written. There are no problems when I runserver or when I do migrations, only when testing:
python manage.py test
_______ERROR MESSAGE:_________
Liams-MBP:GrammieGram Liam2$ python manage.py test grams
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_user" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle
failures = test_runner.run_tests(test_labels)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests
old_config = self.setup_databases()
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases
self.parallel, **kwargs
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases
serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db
run_syncdb=True,
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command
return command.execute(*args, **defaults)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 173, in handle
self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 311, in sync_apps
self.stdout.write(" Running deferred SQL...\n")
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 93, in __exit__
self.execute(sql)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_user" does not exist
My grams/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import datetime
import uuid
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver
"""
#brief A class that describes a user profile.
#field user - the username of the user
#field usertype - the type of user profile (sender/receiver)
#filed contacts - the user's contact book, list of people they can contact
#field admins - and a list of admins, list of users who have admin
privileges over this Profile object
"""
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
usertype = models.CharField(max_length=30, default="sender")
contacts = ArrayField(models.CharField(max_length=150, default="default"), default=[])
admins = ArrayField(models.CharField(max_length=150, default="default"), default=[])
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
"""
#brief Describes a gram message that a sender type Profile is
able to send to a receiver type Profile.
#field send_username - the username of the sender profile
#field recp_username - the username of the receiver profile
#field sent_time - the time at which the Gram object was sent
#field display_until - the amount of time the Gram object will be visible
"""
class Gram(models.Model):
message = models.CharField(max_length=240)
send_username = models.CharField(max_length=150, default="default")
recp_username = models.CharField(max_length=150, default="default")
sent_time = models.DateTimeField(null=True)
display_until = models.DateTimeField(null=True)
def __str__(self):
return self.message
#function checks if another user can be added to the list of contacts
#active_user_type - logged in user; new_contact - the contact to be added
def validated_contact_add(active_user_type,new_contact):
#check if the contact exists in the list of users
if User.objects.filter(username=new_contact).exists():
#check if the type of the logged in user is different from the one being added
if active_user_type != Profile.objects.get(user=User.objects.get(username = new_contact)).usertype:
return "valid"
else:
return "wrong type"
else:
return "does not exist"
_________THINGS I'VE TRIED TO RESOLVE THIS (but failed):_______________
deleting db
deleting local repository and recloning, and deleting db
makemigrations auth and makemigrations (there were no
migrations to make)
using --fake (as suggested in
Django 1.8 test issue: ProgrammingError: relation "auth_user" does not exist)
turning computer on an off again (as you can see, I'm pretty desperate)
Ok, so it turned out that some migrations were being skipped (?) when calling python manage.py makemigrations so I had to specify which app that I wanted to make migrations for. Calling python manage.py makemigrations grams (my target app name) fixed the problem.

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.

Django how to add foreignkey - multiple choices

Hello i created two models and second must use this first, for example first model is product and second is shop which contains few products.
from django.db import models
# Create your models here.
class Product(models.Model):
name = models.CharField("name", max_length=40)
price = models.FloatField("price")
def __unicode__(self):
return self.name
class Shop(models.Model):
product = models.ForeignKey(Product, null = True)
name = models.CharField("shopname", max_length=40)
salary = models.FloatField("salary")
def __unicode__(self):
return self.name
Is it good start? I want create something which will give me possibility to add many Product.models to Shop.model. How to create it?
And second problem is - now when i click
python manage.py migrate homebudget
i have information
(venv) C:\Users\noname\nowe\budget>python manage.py makemigrations homebudget
Migrations for 'homebudget':
0011_auto_20150513_1817.py:
- Alter field price on product
- Alter field name on product
- Alter field name on shop
- Alter field salary on shop
(venv) C:\Users\noname\nowe\budget>python manage.py migrate homebudget
Operations to perform:
Apply all migrations: homebudget
Running migrations:
Rendering model states... DONE
Applying homebudget.0002_shop_product...Traceback (most recent call las
t):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\core\management\__init_
_.py", line 338, in execute_from_command_line
utility.execute()
File "C:\Users\noname\nowe\venv\lib\site-packages\django\core\management\__init_
_.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\core\management\base.py
", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\core\management\base.py
", line 441, in execute
output = self.handle(*args, **options)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\core\management\command
s\migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\migrations\executor.
py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=f
ake_initial)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\migrations\executor.
py", line 147, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\migrations\migration
.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\migrations\operation
s\fields.py", line 62, in database_forwards
field,
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\backends\sqlite3\sch
ema.py", line 176, in add_field
self._remake_table(model, create_fields=[field])
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\backends\sqlite3\sch
ema.py", line 74, in _remake_table
self.effective_default(field)
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\backends\base\schema
.py", line 194, in effective_default
default = field.get_default()
File "C:\Users\noname\nowe\venv\lib\site-packages\django\db\models\fields\relate
d.py", line 1930, in get_default
if isinstance(field_default, self.rel.to):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and typ
es
(venv) C:\Users\noname\nowe\budget>
Running this code doesn't give me any errors, but it looks like nofinator has a point that the field calls don't expect names as positional arguments. If you want them it would probably be better to use verbose_name e.g.,
salary = models.FloatField(verbose_name="salary")
But it doesn't make a lot of sense until you use it to give a more human readable name.
I think you need quotes around 'Product' when defining the foreign key:
product = models.ForeignKey('Product', null = True)
If you need to create a relationship on a model that has not yet been
defined, you can use the name of the model, rather than the model
object itself:
https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey
You probably want to use a models.ManyToManyField not a Foreign Key. The way you have it written now is a Product can have many Shops.
At the very least you'd want the Shop to have many Products; in that case to have a ForeginKey in Product in that case.
You need to write verbose_name="salary", etc. to get rid of the problem.

Using OneToOneField in Django

I'm realized some models in application:
from django.db import models
class Commentary(models.Model):
user_id = models.ForeignKey(User)
created_date = models.DateField()
comment = models.TextField()
class Role(models.Model):
role_name = models.CharField(max_length=25)
class User(models.Model):
login = models.CharField(max_length=50)
password = models.CharField(max_length=50)
address = models.CharField(max_length=255)
phone = models.CharField(max_length=25)
postcode = models.CharField(max_length=25)
email = models.EmailField()
role_id = models.OneToOneField(Role)
After that typed in console "python manage.py makemigration mainws" for making migrations in my database, however, taken stacktrace with error. If looking in django documentation for one-to-one example, we can see the similarity with him, but without option primary_key=True. How can I fix this or maybe better using ForeignKey with unique=True for this issue, or something other?
Stacktrace:
=> python manage.py makemigration mainws
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/savicvalera/code/lab8/website/mainws/models/__init__.py", line 1, in <module>
from . import Commentary, MailList, Product, Provider, Rate, Review, Role, Sale, ShoppingCart, Status, Supplies, User
File "/Users/savicvalera/code/lab8/website/mainws/models/Commentary.py", line 11, in <module>
from . import Product, User
File "/Users/savicvalera/code/lab8/website/mainws/models/User.py", line 14, in <module>
class User(models.Model):
File "/Users/savicvalera/code/lab8/website/mainws/models/User.py", line 21, in User
role_id = models.OneToOneField(Role,to_field='id')
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1799, in __init__
super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs)
File "/Users/savicvalera/code/lab8/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1612, in __init__
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: OneToOneField(<module 'mainws.models.Role' from '/Users/savicvalera/code/lab8/website/mainws/models/Role.pyc'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string u'self'
If I understand your code organization correctly, the problem is in your imports. When you say
from . import Role
you're importing Role.py into a module object named Role. Inside that module (I assume) is your Role model class. So what you really want is:
from .Role import Role
Or:
from . import Role
...
role_id = models.OneToOneField(Role.Role)
You should define an app_label in your meta class
class Foo(models.Model):
class Meta:
app_label = 'mainws'

Categories

Resources