Django AttributeError: module 'clients' has no attribute 'models' - python-3.x

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.

Related

Django 'migrate' command suggesting errors related to packages

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.

Is there a safe way to safely delete a Model field in Django?

I'm making a blog application in Django, and I want to modify a field of the Post class:
I want to change the meta_description field to just description.
From:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
meta_description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
⏎
To:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
When I do that in the model: I have an error Making the migration:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute
self.check()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/DeveloperRode/urls.py", line 26, in <module>
path("blog/", include('blog.urls')),
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/urls.py", line 2, in <module>
from .views import BlogView, ArticleDetail, PostCreateView, EditPost, PostDeleteView
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/views.py", line 8, in <module>
from .forms import PostForm, EditForm
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/forms.py", line 4, in <module>
class PostForm(forms.ModelForm):
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
What Can I do?
The reason this happens is because besides models, you likely have forms, views, serializers, etc. that still use meta_description. If you thus have a PostForm like:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['meta_description']
# change to description &uparrow;
then you should alter this to description as well. You thus should perform a search with meta_description through your project and alter the occurrences of meta_description, but be careful: not all the meta_descriptions per see refer to the field of the Post model, if it is about another model, you of course should not modify this.
I solved the Problem, It seem to be a Form problem, where I was calling the Old field meta_description.
I correct it in forms.py file and make the makemigrations command, after that it showed a prompt:
Did you rename post.meta_description to post.description (a TextField)? [y/N] y
And now there the problem is solved.

Pyinstaller cannot compile project with sklearn

I'm trying to compile this simple python 3 (pyconda) machine learning project with sklearn and these imports (it's a simple Ridge regression predictor):
from datetime import date
import pandas as pd
import numpy as np
from sklearn.linear_model import Ridge
pd.options.mode.chained_assignment = None
class covidUpdater:
situazione = ""
def getCovidUpdate(self):
url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv"
ds = pd.read_csv(url)
return ds.tail(self.giorni)
def __init__(self):
pass
def setGiorni(self,giorni):
self.giorni = giorni
self.situazione = self.getCovidUpdate()
def getCampo(self,campo):
return self.situazione[[campo]]
def getMaxLength(self):
ur1l = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv"
ds1 = pd.read_csv(ur1l)
return len(ds1)
def formatTable(self,campo):
giorniPrediction = 1
updater = covidUpdater()
updater.setGiorni(self.giorni)
updaterFuture = covidUpdater()
updaterFuture.setGiorni(self.giorni+giorniPrediction)
datiCampo = updater.getCampo(campo)
datiCampoFuture = updaterFuture.getCampo(campo)
campo_domani = str(campo) + "_domani"
datiCampo[campo_domani] = datiCampoFuture.shift(-giorniPrediction)
datiCampo = datiCampo.head(self.giorni-giorniPrediction)
datiCampo["id"] = range(datiCampo.iloc[:, 0].size)
return datiCampo
def main():
campo = "nuovi_positivi"
updater = covidUpdater()
giorni = int(input("Inserisci numero giorni da usare come dataset> ") or updater.getMaxLength())
updater.setGiorni(giorni)
print("Giorni selezionati: ",giorni)
df = updater.formatTable(campo)
print("Imposto l'algoritmo di predizione")
X = df.iloc[:, 0].values.reshape(-1,1)
Y = df.iloc[:, 1].values.reshape(-1,1)
regr = Ridge(alpha=1.0,normalize=False,tol=0.1,solver="lsqr")
print("Avvio l'algoritmo di predizione")
regr.fit(X,Y)
Y_pred = regr.predict(X)
print("-----------------------------------\n")
print("Giorni in esame: "+ str(giorni)+"\n")
print("Predizione di (" + str(date.today()) + ") : "+ str(regr.predict(np.array([Y[Y.size-1]])))+"\n")
print("fattore R2: "+ str(regr.score(Y,Y_pred))+"\n")
print("-----------------------------------"+"\n")
if __name__ == "__main__":
main()
By using this command:
pyinstaller --noconfirm --onedir --console --hidden-import "sklearn.linear_model.Ridge" "PATH"
I have this log the final error is:
Traceback
Traceback (most recent call last):
File "d:\pyconda\lib\site-packages\auto_py_to_exe\packaging.py", line 131, in package
run_pyinstaller()
File "d:\pyconda\lib\site-packages\PyInstaller\__main__.py", line 114, in run
run_build(pyi_config, spec_file, **vars(args))
File "d:\pyconda\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 720, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 667, in build
exec(code, spec_namespace)
File "C:\Users\Alex\AppData\Local\Temp\tmp854ytoyk\covid2.spec", line 17, in <module>
noarchive=False)
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 242, in __init__
self.__postinit__()
File "d:\pyconda\lib\site-packages\PyInstaller\building\datastruct.py", line 160, in __postinit__
self.assemble()
File "d:\pyconda\lib\site-packages\PyInstaller\building\build_main.py", line 419, in assemble
self.graph.process_post_graph_hooks()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\analysis.py", line 365, in process_post_graph_hooks
module_hook.post_graph()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\imphook.py", line 440, in post_graph
self._load_hook_module()
File "d:\pyconda\lib\site-packages\PyInstaller\depend\imphook.py", line 407, in _load_hook_module
self.hook_module_name, self.hook_filename)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 588, in importlib_load_source
return mod_loader.load_module()
File "<frozen importlib._bootstrap_external>", line 407, in _check_name_wrapper
File "<frozen importlib._bootstrap_external>", line 907, in load_module
File "<frozen importlib._bootstrap_external>", line 732, in load_module
File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
File "<frozen importlib._bootstrap>", line 696, in _load
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 "d:\pyconda\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-zmq.py", line 21, in <module>
hiddenimports = ['zmq.utils.garbage'] + collect_submodules('zmq.backend')
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 595, in collect_submodules
repr(pkg_dir), package))
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 79, in exec_statement
return __exec_python_cmd(cmd)
File "d:\pyconda\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 68, in __exec_python_cmd
txt = exec_python(*cmd, env=pp_env)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 521, in exec_python
return exec_command(*cmdargs, **kwargs)
File "d:\pyconda\lib\site-packages\PyInstaller\compat.py", line 316, in exec_command
out = out.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 112: invalid start byte
Full log here: https://pastebin.com/XuBeLz3X
I think you should start with the first error in the log:
3560572 INFO: Analyzing hidden import 'sklearn.linear_model.Ridge'
3560576 ERROR: Hidden import 'sklearn.linear_model.Ridge' not found
Have you had a look at this thread with the Hidden import error? How do you resolve 'hidden imports not found!' warnings in pyinstaller for scipy?
I think you need to adjust your hidden imports, so that 'sklearn.linear_model.Ridge' can be found.
And I just tried running your code in Google Colab (https://colab.research.google.com/) and it works there. Perhaps you can run your code there?

python can't use base abstract calass property from subclass gettig AttributeError: 'super' object has no attribute

i dont understand here something that is basic
how can i use property from base which is also abstract class from its sub class
here is small code :
from abc import abstractmethod, ABC
class Base(ABC):
#property
def is_ver0(self):
return None
#abstractmethod
def execute_sql(self):
print("Base execute_sql")
def print_and_exit(self):
print("Base")
And here is the sub class which implemanting the execute_sql and also want to set and get value of
the base is_ver0
Although i can call super().print_and_exit with no problem i can call super().is_ver0
why ?
from base import Base
class Sub(Base):
def __init__(self):
self.execute_sql()
def execute_sql(self):
print("Sub execute_sql")
super().print_and_exit
super().is_ver0 = 1
q = super().is_ver0
print(q)
if __name__ == '__main__':
s = Sub()
s.execute_sql()
but im getting this error :
raceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Dev/python/new_tester/sub.py", line 22, in <module>
s = Sub()
File "C:/Dev/python/new_tester/sub.py", line 10, in __init__
self.execute_sql()
File "C:/Dev/python/new_tester/sub.py", line 16, in execute_sql
super().is_ver0 = 1
AttributeError: 'super' object has no attribute 'is_ver0'
UPDATE still error
i added setter in to base class and still i got error
what basic thing i miss here ?
class Base(ABC):
__xx = None
#property
def is_ver0(self):
return self.__xx
#__xx.setter
def set_x(self,xxx):
self.__xx = xxx
#abstractmethod
def execute_sql(self):
print("Base execute_sql")
def print_and_exit(self):
print("Base")
Traceback (most recent call last):
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:\Dev\python\new_tester\base.py", line 2, in <module>
class Base(ABC):
File "C:\Dev\python\new_tester\base.py", line 8, in Base
#__xx.setter
AttributeError: 'NoneType' object has no attribute 'setter'
You can just set the attribute via self.is_ver0 = 1. However at the moment Base only defines a property without setter, so you need to include a method decorated with #is_ver0.setter that handles the corresponding logic.

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

Resources