Django 'migrate' command suggesting errors related to packages - python-3.x

I am new to Django and python and am presently taking a course on full stack web development, after following the course exactly the way it shows I have typed the following code within the models.py file:
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage)
date = models.DateField()
def __str__(self):
return str(self.date)
And have tried to execute the command:
python manage.py migrate
The following is the error I get when calling this command:
Traceback (most recent call last):
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 22, in <module>
main()
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\config.py", line 224, in create
import_module(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\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 984, in _find_and_load_unlocked
The following is the settings.py file, installed_apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app',
]
And the admin.py file:
from django.contrib import admin
The course showed the models.py file working without adding anything to admin.py, I am not sure why it is showing these errors.

When using foreign keys in your models, you have to set the on_delete parameter so django knows what to do with the entries when the model entry your foreign key is pointing to is deleted.
You could fix your models.py like this:
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.CASCADE)
date = models.DateField()
def __str__(self):
return str(self.date)
You can read more about the different choices you have for this field here and what they are doing.

First of all, in your installed_app list write
INSTALLED_APPS = [
.........
'first_app.apps.FirstAppConfig',
]
insted of just 'first_app'
then in admin.py file add this
from django.contrib import admin
from .models import *
myModels = [models.modelname, models.modelname.......]
admin.site.register(myModels)
then in your cmd first write
python manage.py makemigrations
and then write
python manage.py migrate
Hope this will work.

Related

Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it

I'm currently learning django by tutorial.
So I changed my return-renders to class-generic in views.
in URLs I added as_view() and then it gave me an error.
my traceback:
File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Anaconda3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
databases=databases,
File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter
ns in the file then the issue is probably caused by a circular import.
urls.py:
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:id>/', views.DetailView.as_view(), name='detail'),
path('<int:id>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from .models import Question
from django.template import loader
from django.views import generic
class IndexView(generic.listView):
template_name = 'myapp/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')
class DetailView(generic.DetailView):
model = Question
template_name = 'myapp/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'myapp/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, id=question_id)
try:
selected_choice = question.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'myapp/detail.html',
{'question': question,
'error_message': "You didn't select a choice."}
)
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseResponse(reverse_lazy('myapp:results', args=(question_id,)))
I considered other tutorials and threads but found nothing about my subject. I think I missed something about IDs and PKs.
class IndexView(generic.listView): please change it to class IndexView(generic.ListView):. Here you use listView is incorrect.
I got this error message just bcoz of error in code. I didnt specify the class name when imported the models page
from . models import classname
is the right where this class is used in that page
from . models import
is wrong

Flask AttributeError: module object has no attribute 'app'

I am a newbie to flask, and I had below import related AttributeError when flask run in flask_lab folder.
Any help would be appreciated.
Working Directory:
flask_lab
├── __init__.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── tmp
│   ├── __init__.py
│   └── test.py
└── app.py
flask_lab/app.py:
import os
import click
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_lab.tmp.test.demo
app = Flask(__name__)
prefix = 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
flask_lab.tmp.test.demo()
flask_lab/tmp/test.py:
import flask_lab.app
print(flask_lab.app.db)
def demo():
print('yeah!')
Error:
Traceback (most recent call last):
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/bin/flask", line 10, in <module>
sys.exit(main())
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 894, in main
cli.main(args=args, prog_name=name)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 557, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 767, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 293, in __init__
self._load_unlocked()
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 317, in _load_unlocked
self._app = rv = self.loader()
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 377, in load_app
raise_if_not_found=False)
File "/home/huafeng/.local/share/virtualenvs/flask_lab-x_qc9OjH/lib/python3.6/site-packages/flask/cli.py", line 235, in locate_app
__import__(module_name)
File "/home/huafeng/Desktop/flask_lab/app.py", line 7, in <module>
import flask_lab.tmp.test.demo
File "/home/huafeng/Desktop/flask_lab/tmp/test.py", line 3, in <module>
print(flask_lab.app.db)
AttributeError: module 'flask_lab' has no attribute 'app'
Got complaints from stackoverflow about too many code and not enough details.... more words, more words....
While interpreting app.py if the python interpreter encounters a line import flask_lab.tmp.test.demo then it will start interpreting tmp/test.py immediately. But tmp/test.py again imports flask_lab.
At this point, since the interpreter had already encountered flask_lab, it will start searching for app in that namespace. But it had never reached till that line. Since you had already imported tmp.test before app was defined in the module, there is no flask_lab.app yet and hence the error.
And if you had called tmp.test directly, you would have encountered a circular import error as well.
So the way out is to avoid the circular import scenario. Move the db object to a separate module and call it in both these modules. Flask-SQLAlchemy provides a method called init_app which is meant for such use case.
Lets create a module called common which will contain the common variables.
flask_lab/common.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
flask_lab/app.py:
import os
import click
from flask import Flask
from .common import db
from .tmp.test import demo
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
app = Flask(__name__)
prefix = 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
db.init_app(app)
demo()
flask_lab/tmp/test.py:
from .common import db
print(db)
def demo():
print('yeah!')
Note that I have also replaced the flask_lab imports with relative imports. They are cleaner. The code inside the package should avoid using the package name in the imports. That way if you change the package name later, you can do so without having to change all the code inside.

Unable to import the CustomOperator defined in a python script in plugins folder

I am trying to write a custom operator and sensor in apache-airflow.
It basically has 3 operators and 1 sensor the first operator/task will call some python method and print on the console some message. After that 2nd operator will be called which is a custom operator placed inside a plugins folder in a file named "custom_operator.py". which will insert the data in mongo db database. Then a the custom sensor is called which is using mongo_hook which will monitor the db ans check for the value in db. It is also inside the same file custom_operator.py inside plugins. After this a simple python operator is called.
I have already tried:
Can't import Airflow plugins
```
home/autotest/airflow/dags/custom_dag1.py
import logging
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import date_time, timedelta
from airflow.operators import InsertDb
from airflow.operators import DbSensor
log = logging.getLogger(__name__)
defaultArgs = {
enter code here'owner': 'mohit_saumik',
'depends_on_past': False,
'start_date': date_time(2019,04,11,10,21,23)
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=1)
}
# creating first operator which will print on the console.
def print_operator_one():
log.info("Operator One is executed.")
return "Operator One is executed and returned"
# Creating third operator which will print on the console.
def print_operator_third():
log.info("Operator three is executed")
return "Operator two is executed and returned"
# Creating DAG
dag = DAG('custom_dag', default_args = defaultArgs, schedule_interval=timedelta(minutes=10))
# Creating task 1
operator_one_task = PythonOperator(task_id="task_1", python_callable="print_operator_one", dag=dag)
# Creating task 2
operator_two_task = InsertDb(my_operator_param="This is custom Operator", task_id="task_2", dag=dag)
# Creating Task 3
sensor_one_task = DbSensor(task_id="task_3", poke_interval=10, dag=dag, collection="demoCollection", query={"key1": "value1"})
# Creating task 4
operator_three_task = PythonOperator(task_id="task_4", python_callable="print_operator_third", dag=dag)
# Creating flow
operator_one_task >> operator_two_task >> sensor_one_task >> operator_three_task
```
home/autotest/airflow/plugins/custom_operator.py
import logging
from airflow.models import BaseOperator
from airflow.plugins_manager import AirflowPlugin
from airflow.utils.decorator import apply_defaults
from airflow.contrib.hooks.mongo_hook import MongoHook
from airflow.operators.sensors import BaseSensorOperator
from datetime import datetime
log = logging.getLogger(__name__)
class InsertDb(BaseOperator):
#apply_defaults
def __init__(self, my_operator_param, *args, **kwargs):
self.operator_param = my_operator_param
super(InsertDb, self).__init__(*args, **kwargs)
def execute(self, context):
log.info("Inserting into the DB!")
db_hook = MongoHook(self, conn_id="https://localhost,localhost:27017/mydb")
db_conn = db_hook.get_conn()
insertSuccess = db_conn.insert_one(mongo_collection="demoCollection",doc = {"key1": "value1"}, mongo_db="mydb" )
log.info(insertSuccess)
class DbSensor(BaseSensorOperator):
#apply_defaults
def __init__(self, collection, query, mongo_conn_id="mongo_default", *args, **kwargs):
super(DbSensor,self).__init__(*args,**kwargs)
def poke(self,context):
db_hook = MongoHook(self, conn_id="https://localhost,localhost:27017/mydb")
db_conn = db_hook.get_conn()
result = db_conn.find(mongo_collection=collection, query=query, mongodb="mydb")
if result is None:
log.info("Data not available in DB")
return False
else:
log.info("Data is available in DB")
return True
class DbPlugin(AirflowPlugin):
name = "db_plugin"
operators = [InsertDb, DbSensor]
I am not able to launch the webserver.
Getting the errors:
[2019-04-12 12:35:16,046] {models.py:377} ERROR - Failed to import: /home/autotest/airflow/dags/custom_dag1.py
Traceback (most recent call last):
File "/home/autotest/virtualenv/airflow/lib/python3.6/site-packages/airflow/models.py", line 374, in process_file
m = imp.load_source(mod_name, filepath)
File "/home/autotest/virtualenv/airflow/lib/python3.6/imp.py", line 172, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 684, in _load
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/autotest/airflow/dags/custom_dag1.py", line 41, in <module>
operator_one_task = PythonOperator(task_id="task_1",python_callable="print_operator_one", dag=dag)
File "/home/autotest/virtualenv/airflow/lib/python3.6/site-packages/airflow/utils/decorators.py", line 98, in wrapper
result = func(*args, **kwargs)
File "/home/autotest/virtualenv/airflow/lib/python3.6/site-packages/airflow/operators/python_operator.py", line 81, in __init__
raise AirflowException('`python_callable` param must be callable')
airflow.exceptions.AirflowException: `python_callable` param must be callable
Do it without the quotes: python_callable=print_operator_third. This way you are passing a callable instead of a string.

django and linking tables

I am trying to create a specialized membership application using django. I am having some trouble planning out my app + table structure and data flow. For example: I have the basic django user model. I am using a package called "allauth" and I have created a "Profile" model that holds basic person info. I have tied all that together and it works for sign-up, account verification, logout and getting to a primitive "user page". The next step is where I am getting a bit lost and getting an import error.
The person that creates a log-in must be 18 years old or more. That person might be an adult member or the parent of one or more youth members or be both a parent and an adult member. In any case the logged in person is thought of as being financially responsible for the member-account(s) associated with them. There is also a case where more than one log-in person (like spouses) could share multiple "accounts" between them. For example, either person in an adult couple could be financially responsible for paying the bills.
So, for a given log-in "profile" I need a ManyToMany relation to an "accounts" table. An account can have ManyToMany relations to one or more member records and member "records" should live in the "profile" table but might not have login records in the "User" table.
Now we approach my problem. With the allauth config and an account_adaptor method I have the django "User" model attached to the account profile, a la: (trimmed for brevity)
# PROFILE
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.contrib.auth.models import User
from django.db import models
from .account import Account
class Profile(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
unique=True,
blank=True,
null=True,
)
name_info = ...
birthdate = models.DateField(
blank=False,
null=False
)
address_info = ...
# ACCOUNT
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.db import models
from .student import Student
from Billing.models.payment import Payment
class Account(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
students = models.ManyToManyField(Student)
payments = models.ManyToManyField(Payment)
# STUDENT
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.db import models
from .profile import Profile
class Student(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
profile = models.OneToOneField(
Profile,
on_delete=models.CASCADE,
unique=True,
blank=False,
null=False,
)
When I do makemigrations I get the stacktrace:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\me\myProject\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\me\myProject\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\me\myProject\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\me\myProject\venv\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\me\myProject\venv\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files (x86)\Python3-6-5\lib\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 "C:\me\myProject\myApp\Manager\models\__init__.py", line 2, in <module>
from .group_list import *
File "C:\me\myProject\myApp\Manager\models\group_list.py", line 5, in <module>
from Members.models.profile import Profile
File "C:\me\myProject\myApp\Members\models\__init__.py", line 1, in <module>
from .profile import *
File "C:\me\myProject\myApp\Members\models\profile.py", line 8, in <module>
from .account import Account
File "C:\me\myProject\myApp\Members\models\account.py", line 7, in <module>
from .student import Student
File "C:\me\myProject\myApp\Members\models\student.py", line 7, in <module>
from .profile import Profile
ImportError: cannot import name 'Profile'
My thought is that this is creating some circular linking that django doesn't but I don't understand this well enought to work around it.
Thoughts: the Student table could be its own table but that feels wastful as the Profile table already has the necessary columns
Edit
I think this is a duplicate of this post

Django AttributeError: module 'clients' has no attribute 'models'

I'm running this command python manage.py makemigrations clients and I keep getting an AttributeError. Here are my models;
from django.db import models
import datetime
import calendar
import clients.models
from django.core.urlresolvers import reverse
# Create your models here.
class PartnerInfo(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
phone = models.IntegerField()
price = models.IntegerField()
class NewPartnerLead(models.Model, LeadStage):
new_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
phone_num = models.IntegerField()
lead_stage = LeadStage.lead_stage()
class Booking(models.Model, ClientLead):
number_of_bookings = models.IntegerField()
clients_name = ClientLead.client_name()
clients_phone = ClientLead.phone_number()
clients_email = ClientLead.email_address()
class BookingDetail(Booking):
start_date = datetime.datetime.date()
end_date = datetime.datetime.date()
destination = models.CharField(max_length=50)
#static
def number_of_days(self, start_date, end_date):
return end_date-start_date
class Payment(models.Model, PartnerInfo.price, Booking.BookingDetail.number_of_days):
cash_out = models.IntegerField()
#static
def client_payment(self, number_of_days, price):
return price*number_of_days
#static
def provider_cut(self, client_payment):
provider_cut = 0.8*client_payment
return provider_cut
#static
def balance(self, provider_cut):
provider_cut-cash_out
class Action(Actions):
status = Actions.status()
action = Actions.action()
models on clients.py
class ClientLead(models.Model):
client_name = models.CharField(max_length=100)
phone_number = models.IntegerField()
email_address = models.CharField(max_length=50)
class LeadStage(models.Model):
lead_stage = models.IntegerField()
#static
def lead_status(self, lead_stage):
if lead_stage == 1:
lead_status = 'cold'
if lead_stage == 2:
lead_status = 'interested'
if lead_stage == 3:
lead_status = 'engaged(verbally agreed to pay)'
if lead_stage == 4:
lead_status = 'sold'
return lead_status
class Detail(models.Model, partners.models.Booking):
client = models.ForeignKey(Client_lead, on_delete=models.CASCADE)
destination = models.CharField(max_length=20)
number_of_days = models.IntegerField()
delivery = models.CharField(max_length=4)
start = Bookings.booking_detail.startdate()
end = Bookings.booking_detail.enddate()
class CarDetails(models.Model):
car_type = models.CharField(max_length=50)
car_model = models.CharField(max_length=50)
car_make = models.CharField(max_length=50)
model_year = models.IntegerField()
car_price = models.IntegerField()
#static
def opportunity(self, car_price, number_of_days):
return car_price*number_of_days+delivery
class Actions(models.Model, Leadstage, Detail):
request_start = Detail.start()
request_destination = Detail.destination()
request_delivery = Detail.delivery()
status = models.ForeignKey(Lead_stage, on_delete=models.cascade)
action = models.charfield(max_length=100
when I try the makemigrations command, it raises the aforementioned attribute error. when I import the specific classes I require from partners.models, I get an import error.
Here Is the attribute error it keeps raising:
c:\users\marsha11\source\repos\telemetree\telemetree>python manage.py makemigrations clients
Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
utility.execute()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\core\management\__init__.py", line 338, in execute
django.setup()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\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 "c:\users\marsha11\source\repos\telemetree\telemetree\clients\models.py", line 8, in <module>
import partners.models
File "c:\users\marsha11\source\repos\telemetree\telemetree\partners\models.py", line 19, in <module>
class NewPartnerLead(models.Model, clients.models.LeadStage):
AttributeError: module 'clients' has no attribute 'models'
I've been thinking that its because of the imports but it still is not working and haven't found out why its happening online.

Resources