can not import name 'model' from 'app.model' - 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:

Related

i can not solve 'set' object is not subscriptable in django rest framework

My django project stopped working recently and is showing me 'set' object is not subscriptable error . I want to know how this error can be solved
Here is my 'urls.py'
'''
//this is the urls.py and the error arises from here##
Heading
##
from django.contrib import admin
from django.urls import path,include
from rest_framework import routers
from hotel.views import BookedRoomsViewSet,roomsViewSet,userViewSet,eventViewSet
router = routers.DefaultRouter()
router.register(r'BookedRooms',BookedRoomsViewSet)
router.register(r'Rooms',roomsViewSet)
router.register(r'Users',userViewSet)
router.register(r'Events',eventViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls))
]
Here is the 'models.py' file
'''
from django.db import models
from datetime import date
from django.utils import timezone
# Create your models here.//models.py
class Room(models.Model):
Room_no = models.IntegerField()
Type = models.CharField(max_length=30)
Booked = models.BooleanField(default= False)
class BookedRooms(models.Model):
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
phonenumber = models.CharField(max_length=30)
roomtype = models.CharField(max_length=20)
room = models.ForeignKey(Room,on_delete = models.CASCADE,null = True)
class Users(models.Model):
username = models.CharField(max_length=30)
email = models.EmailField(max_length=30)
password = models.CharField(max_length=10)
class Events(models.Model):
name = models.CharField(max_length=100)
details = models.TextField(max_length=300)
startDate = models.CharField(max_length=12)
startTime = models.TimeField()
endDate = models.CharField(max_length=12)
endTime = models.TimeField()
'''
Here is the 'serializers.py' file
'''
from rest_framework import serializers
from .models import BookedRooms,Room,Users,Events
class RoomSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = BookedRooms
fields = ('id','firstname','lastname','phonenumber','roomtype','room')
class roomSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = Room
fields = ('id','Room_no','Type','Booked')
class userSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model=Users
fields= ('id','username','email','password')
class eventSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = Events
fields = ('id','name','details','startDate','startTime','endDate','endTime')
'''
Here is the 'views.py' file
'''
from django.shortcuts import
from .models import BookedRooms,Room,Users,Events
from .serializers import RoomSerializers,roomSerializers,userSerializers,eventSerializers
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated,
#from rest_framework.views import APIView
# Create your views here.
class BookedRoomsViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = BookedRooms.objects.all()
serializer_class = RoomSerializers
class roomsViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Room.objects.all()
serializer_class = roomSerializers
class userViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Users.objects.all()
serializer_class = userSerializers
class eventViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Events.objects.all()
serializer_class = eventSerializers
'''
I would like if the answers are fast and here is the full traceback
'''
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000008516CD17B8>
Traceback (most recent call last):
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, i
n wrapper
fn(*args, **kwargs)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserve
r.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 37
9, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 36
6, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 71
, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 40, in
check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 57, in
_load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 37, in
__get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 533, in
url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 37, in
__get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 526, in
urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\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 "C:\users\jerry\documents\django-project\vuengo_env\vuengo\vuengo\urls.py", line 18, in <module>
from rest_framework import routers
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 25, in
<module>
from rest_framework import RemovedInDRF311Warning, views
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 17, in <m
odule>
from rest_framework.schemas import DefaultSchema
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\schemas\__init__.py", lin
e 33, in <module>
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\settings.py", line 213, i
n __getattr__
val = self.user_settings[attr]
TypeError: 'set' object is not subscriptable
'''

User Profile 'Syntax Erro'r in Django

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)

Unable to import Model defined in another app

I have two apps appointments and clinic in my project myappointments.
I have defined a model in appointments/models.py:
class Clinicdb(models.Model):
clinicid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=60, unique=True)
label = models.SlugField(max_length=25, unique=True)
email = models.EmailField(max_length=50, default='')
mobile = models.CharField(max_length=15, default='')
alternate = models.CharField(max_length=15, default='', blank=True)
about = models.CharField(max_length=250, blank=True)
state = models.CharField(max_length=25)
city = models.CharField(max_length=35)
locality = models.CharField(max_length=35)
pincode = models.IntegerField(default=0)
address = models.TextField(max_length=80, default='', blank=True)
website = models.URLField(blank=True)
logo = models.ForeignKey(ProfilePic, blank=True, null=True, on_delete=models.CASCADE)
class Meta:
unique_together = ["name", "mobile", "email"]
def __str__(self):
return self.name
In clinic/models.py, I have:
from appointments.models import Clinicdb
class Album (models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(upload_to="data/media/%Y/%m/%d")
clinicid = models.ForeignKey(Clinicdb, blank=True,
null=True, on_delete=models.CASCADE)
def __str__(self):
return self.photo
However when running makemigrations (and runserver) I get:
joel#hp:~/myappointments$ python3 manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/joel/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/joel/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/joel/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/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 "/home/joel/myappointments/appointments/models.py", line 4, in <module>
from clinic.models import Pic, ProfilePic
File "/home/joel/myappointments/clinic/models.py", line 3, in <module>
from appointments.models import Clinicdb
ImportError: cannot import name 'Clinicdb'
You made a cyclic import, if we look at the bottom of the traceback, we see that:
File "/home/joel/myappointments/appointments/models.py", line 4, in <module>
from clinic.models import Pic, ProfilePic
File "/home/joel/myappointments/clinic/models.py", line 3, in <module>
from appointments.models import Clinicdb
So that means that clinic/models.py needs to import appointments/models.py first, but vice versa also holds, hence we can not import this. It comes down to the "chicken and the egg" problem: for an egg, we need a chicken, but for a chicken we need an agg, which results in a logical problem.
What you thus need to do is remove the import, and use a qualified name in a string, like:
# clinic/models.py
# NO import
class Album (models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(upload_to="data/media/%Y/%m/%d")
clinicid = models.ForeignKey('appointment.Clinicdb', blank=True,
null=True, on_delete=models.CASCADE)
def __str__(self):
return self.photo
Django will automatically load the INSTALLED_APPS and replace the qualified string with a reference to the model (in fact one of the reasons of this functionality is solve the circular reference problem).
Note: normally ForeignKeys (and related relation fields) do not end with an id, or _id suffix, so I suggest that you rename clinicid to clinic. This makes sense since a some_album.clinic is not an id of a Clinic, but a Clinic object. Django will automatically add an extra field named clinic_id that stores the id.

django two foreign key for same model

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')

ImportError: cannot import name 'Comment' django 1.9

I am new in django.
I have two app named comments and newapp.I am trying to import one of Class (Comment Class) from comments app to newapp. But I get an error called
ImportError: cannot import name 'Comment'
Here is my 'model.py' from comments app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
# Create your models here.
from newapp.models import NewApp
from newapp.models import Test
class CommentManager(models.Manager):
def filter_by_instance(self, instance):
content_type = ContentType.objects.get_for_model(instance.__class__)
obj_id = instance.id
qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)
return qs
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
#post = models.ForeignKey(NewApp)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
def __unicode__(self):
return str(self.user.username)
def __str__(self):
return str(self.user.username)
Here is the 'model.py' code for newapp app
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify
#here is the problem code to import below class
from comments.models import Comment
# Create your models here.
class NewApp(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.FileField(null=True, blank=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def _unicode_(self):
return self.title
def _str_(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug":self.slug})
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
# #property
# def comments(self):
# instance = self
# qs = Comment.objects.filter_by_instance(instance)
# return qs
class Test(models.Model):
def _unicode_(self):
return self.title
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = NewApp.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=NewApp)
INSTALLED APP from setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'comments',
'newapp',
]
And finnaly i got error like this
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x039B27C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 13, in <module>
import django.comments
ImportError: No module named 'django.comments'
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
at 0x034627C8>
Traceback (most recent call last):
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\site-packages
\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\eXp\AppData\Local\Programs\Python\Python35-32\lib\importlib\__i
nit__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\eXp\Desktop\venv\mysite\comments\models.py", line 8, in <module
>
from newapp.models import NewApp
File "C:\Users\eXp\Desktop\venv\mysite\newapp\models.py", line 14, in <module>
from comments.models import Comment
ImportError: cannot import name 'Comment'
You're importing newapp from comments and comments from newapp. In python, you can't have circular imports like this. Quick fix: remove the import from newapp inside comments's models.py and replace with a name reference, like this:
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
post = models.ForeignKey('newapp.NewApp') # <= HERE
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()