my model
class BaseModel(models.Model):
CreatedDate = models.DateTimeField(auto_now_add=True, verbose_name="Oluşturulma Tarihi")
ModifiedDate = models.DateTimeField(auto_now=True, verbose_name="Son Güncellenme tarihi")
Isdeleted = models.BooleanField(verbose_name="Silindi", default=False)
class Case(BaseModel):
CaseNumber = models.CharField(max_length=14)
Customer = models.ForeignKey(Customer)
Title = models.ForeignKey(CaseTitle)
CaseCategory = models.ForeignKey(CaseCategory, verbose_name="Kategori")
Priority = models.ForeignKey(CasePriority)
Status = models.ForeignKey(CaseStatus)
Detail = models.TextField()
Group = models.ForeignKey(Group)
User = models.ForeignKey(User,related_name='User' )
AssignedUser = models.ForeignKey(User,related_name='AssignedUser')
CloseDetail = models.TextField blank=True)
i just want to give 2 foreign key this my model but error is
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 796, in __init__
to._meta.model_name AttributeError: 'ForeignKey' object has no attribute '_meta'
During handling of the above exception, another exception occurred:
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 338, in execute
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/code/Case/models.py", line 91, in <module>
class Case(BaseModel):
File "/code/Case/models.py", line 101, in Case
AssignedUser = models.ForeignKey(User,related_name='AssignedUser')
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 802, in __init__
RECURSIVE_RELATIONSHIP_CONSTANT, AssertionError: ForeignKey(<django.db.models.fields.related.ForeignKey>) is invalid.
First parameter to ForeignKey must be either a model, a model name, or the string 'self'
You're redefining User The relevant section of Django code this is bombing on is an isinstance(to, str) which means User is not a model but it's also not a string (it's a ForeignKey).
If you're using Django's User model or a customized variant the correct way to obtain a reference independently is to use django.contrib.auth.get_user_model(). e.g.:
from django.contrib.auth import get_user_model
User = get_user_model()
class MyModel(models.Model):
user = models.ForeignKey(User)
In Python it's convention to lowercase names unless they are classes.
Does it work if you only implement one relationship to the model User? The error message:
First parameter to ForeignKey must be either a model, a model name, or the string 'self'
lets me assume, that you're not passing the actual class of the User model. How do you obtain it?
Also, from looking at the fields of BaseModel I suppose, it could be an abstract base model:
class BaseModel(models.Model):
class Meta:
abstract = True
CreatedDate = models.DateTimeField(auto_now_add=True, verbose_name="Oluşturulma Tarihi")
...
See here for more information: https://godjango.com/blog/django-abstract-base-class-model-inheritance/
You should be following the python conventions on how to use uppercase, lowercase, otherwise the interpreter is going to refer to wrong variables:
Classes are the only things that should be camel-case (class User, class CaseTitle).
Your class properties (instance variables) should be lowercase with underscores: case_number, user, assigned_user, etc...
When you write User = ForeignKey(User) you're actually redefining the User variable, so in the next line AssignedUser = ForeignKey(User), User isn't the User model class anymore. If I write it out, I get:
AssignedUser = models.ForeignKey( # User
models.ForeignKey( # User
models.ForeignKey( # User etc...
...
Change the field name User to anything you want. It conflicts that's why you get the error.
class Case(BaseModel):
....
user = models.ForeignKey(User,related_name='user' )
assigned_user = models.ForeignKey(User,related_name='assigned_user')
Related
I'm trying to create a Formview wait.
First of all where should I create the Meta class? I saw a page first where it create the Meta class inside the models but then I saw another page where it says that I should create in my forms. So I did that also and then I saw another page where it say that it must register the models in admin because I also had that error where it show an error if I miss an "s" in Meta class models description.
Here's my error:
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /registry.py", line 77, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 23, in check_resolver
return check_method()
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check
for pattern in self.url_patterns:
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 632, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 625, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/laboratory-01/Desktop/folder1/School/School/urls.py", line 18, in <module>
from principal.views import *
File "/home/laboratory-01/Desktop/folder1/School/principal/views.py", line 7, in <module>
from .forms import *
File "/home/laboratory-01/Desktop/folder1/School/principal/forms.py", line 26, in <module>
class RegForm(ModelForm):
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/forms/models.py", line 259, in __new__
fields = fields_for_model(
File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/forms/models.py", line 148, in fields_for_model
opts = model._meta
AttributeError: 'tuple' object has no attribute '_meta'
And here's my forms:
class RegForm(ModelForm):
class Meta:
model = Users
fields = ['name', 'lname1']
Nombre = forms.CharField(label="Nombre", max_length=100, required=False)
ApellidoPaterno = forms.CharField(max_length=100, required=False)
ApellidoMaterno = forms.CharField(max_length=100, required=False)
User = forms.ChoiceField(label="Eres?", choices=Users)
lugarDeNacimiento = forms.ChoiceField(label="Pais", choices=Paises)
FechaNacimiento = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today)
foto = forms.ImageField(label="foto")
Email = forms.EmailField(required=True)
passwd = forms.CharField(label="contraseña",max_length=32,widget=forms.PasswordInput)
ConfPasswd = forms.CharField(label="confirmar contraseña", max_length=100, widget=forms.PasswordInput)
And here's my models where I also put the formclass. I don't know why:
class Users(models.Model):
name = models.CharField(max_length=100, primary_key=True)
lname1 = models.CharField(max_length=100)
lname2 = models.CharField(max_length=100)
age = models.IntegerField()
user_name = models.CharField(max_length=12, choices=users)
imagen = models.ImageField()
birthday = models.DateField(auto_now_add=False)
country = models.CharField(max_length=12, choices=paises)
Email = models.EmailField( )
idCard = models.IntegerField()
psswd = models.CharField(max_length=90)
conf_psswd = models.CharField(max_length=100)
def __str__(self):
return self.nombre
class RegForm(ModelForm):
class Meta:
Model = Users
or am I registering the models wrong in the admin file because I also have to say that I have three applications in a project it's profesores estudiantes principal where principal should be my authentication tools of Django.
I have two apps 'user' and 'game' and here is my user/models.py:
from django.db import models
from django.db.models.fields import related
from django.contrib.auth.models import AbstractBaseUser , User,
AbstractUser , PermissionsMixin
from .managers import CustomUserManager
from game.models import Game
class User(AbstractBaseUser,PermissionsMixin):
username = models.CharField(max_length=150,
unique=True, blank=True , null=True,)
email = models.EmailField( blank=True , null=True , unique=True)
password = models.CharField(max_length=100, null=True , blank=True)
objects = CustomUserManager()
class Meta:
db_table = 'user'
class Team(models.Model):
name = models.CharField(max_length=40, unique=True)
players = models.ManyToManyField(User,
related_name="players")
game = models.ManyToManyField(Game)
is_verfied = models.BooleanField(default=False)
class Meta:
db_table = 'team'
and here is my game/models.py:
from django.db import models
from user.models import User, Team
from leaga.settings import AUTH_USER_MODEL
class Game(models.Model):
name = models.CharField(max_length=50)
is_multiplayer = models.BooleanField(default=False)
class Event(models.Model):
title = models.CharField(max_length=100)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
class Tournament(models.Model):
title = models.CharField(max_length=50)
is_team = models.BooleanField(default=False)
price = models.PositiveIntegerField()
info = models.TextField(max_length=1000)
user = models.ManyToManyField(AUTH_USER_MODEL,
related_name='tounament_user')
team = models.ManyToManyField(Team, related_name='team')
game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='tournament_game')
event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='tournament_event')
# some other code and classes here but unnecessary to mention
.
.
.
.
when i run :
python manage.py makemigrations user
this is the console log:
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 "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/amir/Desktop/leaga/leaga/user/models.py", line 6, in <module>
from game.models import Game
File "/Users/amir/Desktop/leaga/leaga/game/models.py", line 3, in <module>
from user.models import Team
ImportError: cannot import name 'Team' from 'user.models' (/Users/amir/Desktop/leaga/leaga/user/models.py)
I tried to delete all .pyc files from my project
also, drop the entire database and create again(i know it's probably not the point but I got angry and I dropped the entire database and recreate it
File "/Users/amir/Desktop/leaga/leaga/user/models.py", line 6, in
from game.models import Game
File "/Users/amir/Desktop/leaga/leaga/game/models.py", line 3, in
from user.models import Team
ImportError: cannot import name 'Team' from 'user.models' (/Users/amir/Desktop/leaga/leaga/user/models.py)
From the message we can see that this is due to circular imports.
user/models.py tries to import the Game model from game/models.py, and game/models.py tries to import the Team model from user/models.py.
One solution is to remove:
from game.models import Game
From user/models.py, and change:
game = models.ManyToManyField(Game)
To:
game = models.ManyToManyField('game.Game')
You might want to read: ForeignKey and ManyToManyField.
Relevant part copied here:
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:
I am trying to create the user profile in Django. t is a new User model that inherits from AbstractUser. It requires special care and to update some references through the settings.py. Ideally, it should be done at the beginning of the project, since it will dramatically impact the database schema. Extra care while implementing it.
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/home/user/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 674, in exec_module
File "<frozen importlib._bootstrap_external>", line 781, in get_code
File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/user/Desktop/vmail/vm/models.py", line 21
user = models.OneToOneField(User, on_delete=models, CASCADE)
^
SyntaxError: positional argument follows keyword argument
how to solve this syntax error?
my models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class login(models.Model):
title=models.CharField(max_length=50, blank=True, null=True)
content=models.TextField(blank=True, null=True)
date=models.DateTimeField(default=timezone.now())
def __str__(self):
return self.title
class UserProfileModel(models.Model):
user = models.OneToOneField(User, on_delete=models, CASCADE)
gender = models.CharField(max_length='1', choices=(('M','Male'),('F','Female')), blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
def __str__(self):
return self.user.username
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
Change this to
user = models.OneToOneField(User, on_delete=models.CASCADE)
In AdminForm I prevent the user from duplicating the records.
from django import forms
from django.contrib.auth.models import User
from apps.accounting_users.models import AccountingUser
from apps.marketing_users.models import MarketingUser
from apps.mgmt_users.models import ManagementUser
from apps.serv_mgrs_users.models import ServiceMgmtUser
from apps.serv_staff_users.models import ServiceStaffUser
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(
queryset=User.objects.exclude(
username__in=[record.user.username for record in AccountingUser.objects.all()] +
[record.user.username for record in MarketingUser.objects.all()] +
[record.user.username for record in ManagementUser.objects.all()] +
[record.user.username for record in ServiceMgmtUser.objects.all()] +
[record.user.username for record in ServiceStaffUser.objects.all()],
)
)
mgmt_users/models.py
from apps.commons.models import AbstractSBrandUser
class ManagementUser(AbstractSBrandUser):
pass
commons/models
class AbstractSBrandUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True)
mobile = models.CharField(max_length=15)
class Meta:
abstract = True
OSX 10.12.4 pytest is normal
Debian:Jessie is broken
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/buddy/siam-sbrand/portal/apps/mgmt_users/admin.py", line 3, in <module>
from apps.commons.forms import BaseDjangoAdminRoleForm
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 11, in <module>
class BaseDjangoAdminRoleForm(forms.ModelForm):
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 17, in BaseDjangoAdminRoleForm
[record.user.username for record in ServiceMgmtUser.objects.all()] +
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 1087, in _fetch_all
Question:
I had checked the syntax based on python3 already.
And I had checked the filter syntax of Django1.10 already.
python manage.py shell run fine. No error at all.
How can I use queryset in the AdminForm of the Django and pass the test?
Do I need to sacrify testing for this feature?
You can't use querysets like [record.user.username for record in AccountingUser.objects.all()] in your model form definition. Django tries to evaluate the queryset when the module is loaded. If the table has not been created yet, this will give an error.
You can fix the problem by setting the queryset in the __init__ method.
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.none())
def __init__(self, *args, **kwargs):
super(BaseDjangoAdminRoleForm, self).__init__(*args, **kwargs)
self.fields['user'].queryset = User.objects.exclude(...)
This has the advantage of evaluating the usernames every time the form is created - at the moment, they are only evaluated once when the server starts.
Django 1.5 & Python 3.2.3, on Ubuntu 12.04.
Very odd error when trying to syncdb my DB. I've got some fields that don't look wrong but Django's spitting out this error message when I run python3 manage.py sqlall..
NameError: name 'PositiveSmallIntegerField' is not defined
Huh? I tried Googling this, but there's not a single thing about it anywhere. So I'm guessing I've made some stupid mistake but I can't see it. My models.py looks like this:
from django.db import models
class Song(models.Model):
own = models.BooleanField(default=True)
heard = models.DateTimeField(blank=True,null=True)
release_date = models.DateField(blank=True,null=True)
style = models.CharField(max_length=255,blank=True,null=True)
artist = models.CharField(max_length=255,blank=True,null=True)
featuring = models.CharField(max_length=255,blank=True,null=True)
title = models.CharField(max_length=255,blank=True,null=True)
listen = models.URLField(max_length=255,blank=True,null=True)
highest_chart_pos = models.PositiveSmallIntegerField()
note = models.TextField(blank=True,null=True)
That's all there is to it, and I copy-n-pasted PositiveSmallIntegerField straight from the Django documentation so I know there isn't a typo in it that I'm overlooking. So, how is PositiveSmallIntegerField not defined?
Throwing this in here because I found myself with the same error, creating a model for a
song, too!
from django.db import models
class Track(models.Model):
release = models.ForeignKey('Release', on_delete=models.CASCADE)
position = models.PositiveSmallIntegerField()
number = PositiveSmallIntegerField()
name = models.CharField(max_length=100)
length = models.DurationField()
There is a slight difference, here. I left out the namespace of models. before my PositiveSmallIntegerField. It looks like you didn't do that, above, but maybe someone else with a similar error will made my mistake, too.
Here was my stacktrace:
(env) Cam#cambook:~/Sites/juke% python manage.py makemigrations playlists
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/Cam/Sites/juke/playlists/models.py", line 60, in <module>
class Track(models.Model):
File "/Users/Cam/Sites/juke/playlists/models.py", line 63, in Track
number = PositiveSmallIntegerField()
NameError: name 'PositiveSmallIntegerField' is not defined