I have both versions python 2.7 and 3.4 installed. I am using some code which is developed under 2.7 but I am using under 3.4. So after compiling using the following command
python manage.py runserver
I get the following error -
File "C:\pyprojects\focus\site\general\forms.py", line 26, in Meta
model = models.UserProfile
AttributeError: 'module' object has no attribute 'UserProfile'
The directory structure is
├───focus
│ ├───data_dumps
│ ├───notes
│ ├───setup
│ └───site(main project folder)
| └───static
| └───general
| +--forms.py
| +--models.py
| └───pro
| └───models
| +--__init__.py
| +--plans.py
│ └───focus2
│ └───templates
| +--__init__.py
│ +--settings.py
│ +--util.py
│ +--wsgi.py
│ +--manage.py
As models.py and forms.py is under same directory(general) so I have imported the model in forms.py in this way
from .models import models
Now in models.py I have defined the class
class UserProfile(models.Model, HashedPk):
user = models.OneToOneField(User, unique=True)
is_pro = models.BooleanField(default=False, blank=True)
......................................................
In forms.py the code is
class UserProfileForm(forms.ModelForm):
class Meta:
model = models.UserProfile
.....................
Is there any special way to call the model in python 3.4.
Any help is highly appreciated.
It's sorted. The import needs to be
from . import models
instead
from .models import models
Related
I tried to follow this tutorial
https://blog.nicolasmesa.co/posts/2018/10/saas-like-isolation-in-django-rest-framework/
using: Django 3.1 Python 3.6
Everything I did including 'The User Messages App' paragraph worked perfectly right before the 'Refactoring the views' passage
and then I got the error when running manage.py runserver
django.core.exceptions.ImproperlyConfigured: The included URLconf 'saas_django.urls' does not appear to have any pa
tterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import
I tried different types of import but I can't figure out where the cirular import happens
My steps to find a bug:
the
saas_django/urls.py refers to user_messages app:
path('api/v1/user-messages/', include('user_messages.urls')),
user_messages/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.UserMessageList.as_view(),
name=views.UserMessageList.name),
path('<uuid:pk>', views.UserMessageDetail.as_view(),
name=views.UserMessageDetail.name),
]
It seems like something is wrong with the imported user_messages/views.py
from rest_framework import permissions
from rest_framework import generics
from . import serializers
from .models import UserMessage
class UserMessageList(generics.ListCreateAPIView):
name = 'usermessage-list'
permission_classes = (
permissions.IsAuthenticated,
)
serializer_class = serializers.UserMessageSerializer
queryset = UserMessage.objects.all()
def perform_create(self, serializer):
user = self.request.user
company_id = user.company_id
# Added from_user
serializer.save(company_id=company_id, from_user=user)
def get_queryset(self):
# Changed this to use the UserMessageManager's method
return UserMessage.objects.get_for_user(self.request.user)
class UserMessageDetail(generics.RetrieveAPIView):
name = 'usermessage-detail'
permission_classes = (
permissions.IsAuthenticated,
)
serializer_class = serializers.UserMessageSerializer
def get_queryset(self):
# Changed this to use the UserMessageManager's method
return UserMessage.objects.get_for_user(self.request.user)
I gues the cause of the error is something about these 2 lines:
from . import serializers
from .models import UserMessage
the user_messages/serializers.py also has the import of UserMessages
from rest_framework import permissions
from rest_framework import generics
from . import serializers
from .models import UserMessage
class UserMessageList(generics.ListCreateAPIView):
name = 'usermessage-list'
permission_classes = (
permissions.IsAuthenticated,
)
serializer_class = serializers.UserMessageSerializer
queryset = UserMessage.objects.all()
def perform_create(self, serializer):
user = self.request.user
company_id = user.company_id
# Added from_user
serializer.save(company_id=company_id, from_user=user)
def get_queryset(self):
# Changed this to use the UserMessageManager's method
return UserMessage.objects.get_for_user(self.request.user)
class UserMessageDetail(generics.RetrieveAPIView):
name = 'usermessage-detail'
permission_classes = (
permissions.IsAuthenticated,
)
serializer_class = serializers.UserMessageSerializer
def get_queryset(self):
# Changed this to use the UserMessageManager's method
return UserMessage.objects.get_for_user(self.request.user)
I tried to rewrite import as:
from .models import UserMessage as UM
but it didn't work.
Project structure is:
│ db.sqlite3
│ manage.py
│ sqlite3.exe
│
├───accounts
│ admin.py
│ apps.py
│ models.py
│ serializers.py
│ tests.py
│ urls.py
│ views.py
│ __init__.py
│
├───core
│ models.py
│ serializers.py
│ views.py
│ __init__.py
│
├───saas_django
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───user_messages
│ admin.py
│ apps.py
│ models.py
│ serializers.py
│ tests.py
│ urls.py
│ views.py
│ __init__.py
│
├───migrations
My full code is here: https://github.com/SergSm/test-django-saas/
The question is how to properly debug this type of error?
First of all there are few issues in the project itself. There are unresolved references to serializers without which no one will be able to help out. For example:
from core.serializers import CompanySafeSerializerMixin
This is referenced in a few other serializers. Also, other than this, there is one major issue in the way you have defined the models for:
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company,
related_name='%(class)s',
on_delete=models.CASCADE,
editable=False,
default=get_default_company)
The default method looks like this:
def get_default_company():
"""get or create the non existent company for new users"""
return Company.objects.get_or_create(is_default_company=True,
name=DEFAULT_COMPANY)[0].pk
Not sure in what sequence you made these models but since you have not pushed your migrations onto the VCS, this will cause the issue.
Remember, always push your migrations on the VCS.
I cannot highlight this enough. It can lead to serious issues as and when the project grows.
Else, on new setup, Django will never be able to identify correct dependency between models.
Coming to the other problem, since you have used default as method that gets ref from another model, Django will not allow me to make the migrations in the first place since the model itself that its referring to is not yet made.
File "/home/dhwanil/work/packages/test-django-saas/venv/lib64/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "companies" does not exist
LINE 1: ...."address", "companies"."is_default_company" FROM "companies...
^
This would have been solved if lets say you had 0001_initial one with the company model and the 0002_users where you refer the Company model. Also, you might want to look at the concept of fixtures that will help you populate a model on every fresh installation.
Coming to the main question you asked, if its indeed a circular, the best way is to closely inspect the traceback, it would show where the circular dep lies. Since I am unable to setup the project until the above mentioned issues are solved, I will not be able to give you a more directed answer.
Summary:
Always push the migrations that are created after python manage.py makemigrations on the VCS, migrations are like commits of the state of your DB, you cannot expect to work with latest state without knowing the steps it was built from.
Avoid using methods to get default from another model, the better way is always use fixtures to first populate the DB. Again, this will not be possible without splitting your migrations smartly.
return Company.objects.get_or_create(is_default_company=True,
name=DEFAULT_COMPANY)[0].pk
Alternative to use fixtures would be "Data Migrations", I always recommend to add a custom RunPython code in your migrations to assign defaults. This takes off the overhead of worrying if the data is there in the DB or not, because it will be populated the moment you run migrate.
Most circular imports can be identified by the traceback, inspect it closely.
That's all for now, if you fix the import issues, let me know. I'll be happy to take a look.
Cheers!
I have created a new app "grn" in my django project and tried to import the models from another app named "packsapp" in the same project like this:
Models.py
from ..packsapp.models import *
But I got the following error:
ValueError: attempted relative import beyond top-level package
Here's the structure of the app:
yantra_packs
grn
--migrations
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
media
packsapp
--migrations
templates
templatetags
views1
__init__.py
apps.py
decorators.py
forms.py
models.py
urls.py
views.py
How can I import the models of the packsapp in the grn ??
The root directory of a Django project is not a Python package or module. So relative imports across Django apps will not work. Use an absolute import instead:
from packsapp.models import *
I am trying to run scrapy with DjangoItem. When i run crawl my spider, I get the 'ExampleDotComItem does not support field: title' error. I have created multiple projects and tried to get it to work but always get the same error. I found this tutorial and downloaded the source code, and after running it; I get the same error:
Traceback (most recent call last):
File "c:\programdata\anaconda3\lib\site-packages\twisted\internet\defer.py",line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "C:\Users\A\Desktop\django1.7-scrapy1.0.3-master\example_bot\example_bot\spiders\example.py", line 12, in parse
return ExampleDotComItem(title=title, description=description)
File "c:\programdata\anaconda3\lib\site-packages\scrapy_djangoitem__init__.py", line 29, in init
super(DjangoItem, self).init(*args, **kwargs)
File "c:\programdata\anaconda3\lib\site-packages\scrapy\item.py", line 56, in init
self[k] = v
File "c:\programdata\anaconda3\lib\site-packages\scrapy\item.py", line 66,
in setitem
(self.class.name, key)) KeyError: 'ExampleDotComItem does not support field: title'
Project structure:
├───django1.7-scrapy1.0.3-master
├───example_bot
│ └───example_bot
│ ├───spiders
│ │ └───__pycache__
│ └───__pycache__
└───example_project
├───app
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
└───example_project
└───__pycache__
My Django Model:
from django.db import models
class ExampleDotCom(models.Model):
title = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __str__(self):
return self.title
My "example" Spider:
from scrapy.spiders import BaseSpider
from example_bot.items import ExampleDotComItem
class ExampleSpider(BaseSpider):
name = "example"
allowed_domains = ["example.com"]
start_urls = ['http://www.example.com/']
def parse(self, response):
title = response.xpath('//title/text()').extract()[0]
description = response.xpath('//body/div/p/text()').extract()[0]
return ExampleDotComItem(title=title, description=description)
Items.py:
from scrapy_djangoitem import DjangoItem
from app.models import ExampleDotCom
class ExampleDotComItem(DjangoItem):
django_model = ExampleDotCom
pipelines.py:
class ExPipeline(object):
def process_item(self, item, spider):
print(item)
item.save()
return item
settings.py:
import os
import sys
DJANGO_PROJECT_PATH = '/Users/A/DESKTOP/django1.7-scrapy1.0.3-master/example_project'
DJANGO_SETTINGS_MODULE = 'example_project.settings' #Assuming your django application's name is example_project
sys.path.insert(0, DJANGO_PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE
BOT_NAME = 'example_bot'
import django
django.setup()
SPIDER_MODULES = ['example_bot.spiders']
ITEM_PIPELINES = {
'example_bot.pipelines.ExPipeline': 1000,
}
Can you show your Django model? This is likely occurring because title isn't defined on your ExampleDotCom model.
If it is there, perhaps you need to run your Django migrations?
What is the proper way to say what is my AUTH_USER_MODEL?
I have the following set:
Folder structure:
--- backend
----- api
-------- models
----------- user.py
user.py lies within models folder
in settings.py:
AUTH_USER_MODEL = 'myapp.User'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'api',
]
The model:
class User:
class Meta:
app_label = "myapp"
And when I run any manage.py command, for example
python manage.py showmigrations
I get this error:
LookupError: No installed app with label 'myapp'.
The problem solution would be renaming api folder to myapp, which I cannot do due to some restrictions on model names. Or setting AUTH_USER_MODEL to api.User, but this will incur changing all data table names and those must remain the same
Data table names starting with 'myapp_' should not change
Given your folder structure looks like that:
backend
└── api
| ├── __init__.py
| ├── apps.py
| └── models
| ├── __init__.py
| └── user.py
├── manage.py
└── settings.py
then you can create an app config in backend/api/ by creating a file called apps.py inside it. There you can rename your app:
backend/api/apps.py:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
verbose_name = _('My App')
Also you need to add this to the __init__.py inside that folder:
backend/api/__init__.py:
default_app_config = 'api.apps.MyAppConfig'
Also if you want to use myapp.User as your user model you also have to import in in the models module:
backend/api/models/__init__.py:
from .user import User
# or use "from .user import *" to import everything but then make sure you have __all__ defined in user.py
The solution was to change AppConfig.label in class MyAppConfig(AppConfig), so if you update your answer, I will accept it. Changing name ends in nothing, it must be the real name of the module the code sits in, but adding label = 'arbitrary_name' is actually the solution
So I am following a Django tutorial and I have the following directory for a project:
demo/
demo/
apps/
ventas/
__init__.py
admin.py
models.py
tests.py
views.py
__init.py
__init__.py
settings.py
urls.py
wsgi.py
manage
And under admin.py I have:
from django.contrib import admin
from demo.apps.ventas.models import cliente.producto
# Register the ventas models
admin.site.register(cliente)
admin.site.register(producto)
And from models.py,
from django.db import models
class cliente(models.Model):
nombre = models.CharField(max_length=200)
apellido = models.CharField(max_length=200)
status = models.BooleanField(default=True)
class producto(models.Model):
nombre = models.CharField(max_length=200)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
But when I run python manage.py runserver from Django_tutorial2/demo, I received the
SyntaxErrro in admin.py, line 2 in localhost:8000. It still worked before I added the ventas folder.
What is wrong?
I think you want
from demo.apps.ventas.models import cliente, producto
This will import the class cliente and the class producto.
from demo.apps.ventas.models import cliente.producto
replace it with:
from demo.apps.ventas.models import cliente, producto