Unable to import model form model of another app - django

This is code of transactions.model
here i am trying to import WalletUser model form WalletUser.models
import uuid as uuid
from django.db import models
from walletApp.WalletUser.models import WalletUser
class Transaction(models.Model):
STATUS_TYPES = (
('C', 'Compleat'),
('S', 'Success'),
('I', 'Incompleat'),
('A', 'aborted'),
)
uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, db_index=True)
status = models.CharField(choices=STATUS_TYPES, default='N', max_length=3)
created_on = models.DateTimeField(auto_now_add=True, null=False)
user = models.ForeignKey(WalletUser)
amount = models.FloatField()
def __str__(self):
return self.uuid
I am getting this error
/Users/shoaib/Documents/walletTransactionSystem/walletApp/walletApp/settings.py changed,
reloading.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/Users/shoaib/Documents/walletTransactionSystem/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/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/shoaib/Documents/walletTransactionSystem/walletApp/transaction/models.py", line 4, in <module>
from walletApp.WalletUser.models import WalletUser
ModuleNotFoundError: No module named 'walletApp.WalletUser'
I tried walletApp.WalletUser.models and WalletUser.models too both are not working.
WalletUser.models is straight up giving.
PLZ help I am stuck

from WalletUser.models import WalletUser
You are very close! Since your app is in the same directory as the base, you don't need to specify base directory, you can just import the models from the app.

Related

not able to start the start the server djano

updated version
# Create your models here.
class PlacedOrder(models.Model):
restraunt = models.ForeignKey(Restraunts, on_delete=models.CASCADE)
order_time = models.TimeField(
auto_now_add=True)
estimated_delivery_time = models.TimeField()
actual_delivery_time = models.TimeField()
food_ready_time = models.TimeField()
total_price = models.DecimalField(9, 2)
I am getting this error for no reason, not knowing where the problem lies, it's not allowing me to run migrations as well, I have posted by trace below, need help with this
"C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\atif\PycharmProjects\my_proj_basic\food_deliveryapp\orders\models.py", line 9, in <module>
class PlacedOrder(models.Model):
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 161, in __new__
new_class.add_to_class(obj_name, obj)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class
value.contribute_to_class(cls, name)
File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\models\fields\__init__.py", line 788, in contribute_to_class
if not getattr(cls, self.attname, None):
TypeError: getattr(): attribute name must be string
May be you are missing the attribute name.
price = models.DecimalField(15, 2,)
Try This:
price = models.DecimalField(max_digits=15, decimal_places=2,)

How can I fix the issue: No module named 'multiselectfield'?

I installed django-multiselectfield successfully but it doesn't work. these steps I did to run the lib:
pip3 install django-multiselectfield
INSTALLED_APPS = [
#...,
'multiselectfield'
]
also, I did create requirements.txt file but the error didn't go, How can I install this lib successfully
models.py
from multiselectfield import MultiSelectField
class PlayerName(models.Model):
match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='player_name')
name = models.CharField(max_length=255)
def __str__(self):
return self.name
PLAYERS = PlayerName.objects.values_list('name', 'name')
class PlayerBox(models.Model):
player_name = models.ForeignKey(PlayerName, on_delete=models.CASCADE, related_name='player_box')
name = MultiSelectField(choices=PLAYERS)
Edit post
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
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 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'multiselectfield'

Django - set a model CharField value to the name of a field from another model

I have a model when I want to field_name to be the name of any field from another model.
I wrote this code:
from providers.models import Organisation
FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ]
class Score (models.Model):
field_name = models.CharField(max_length=101, choices=FIELD_CHOICES)
When I run makemigrations I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
This is the complete traceback:
Traceback (most recent call last):
File "./src/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/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/henry/Documents/Sites/Development/autumna-dev/autumna/src/scoring/models.py", line 7, in <module>
FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ]
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 733, in get_fields
return self._get_fields(include_parents=include_parents, include_hidden=include_hidden)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 793, in _get_fields
all_fields = self._relation_tree
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 706, in _relation_tree
return self._populate_directed_relation_graph()
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 677, in _populate_directed_relation_graph
all_models = self.apps.get_models(include_auto_created=True)
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 175, in get_models
self.check_models_ready()
File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 137, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Return just the last object in Django REST Framework

I'm new to asking on StackOverflow and to Django so I'm sorry if I made any mistakes.
So far, I have a basic API with Django and REST Framework. I want to return just the last object that was added to the database, which could be done with the highest ID.
This is the models.py:
from django.db import models
class Humidity(models.Model):
value = models.FloatField()
class Temperature(models.Model):
value = models.FloatField()
isFarenheit = models.BooleanField()
I don't have any time fields, but I can add them if necessary.
This is the serializers.py:
class HumiditySerializer(serializers.ModelSerializer):
class Meta:
model = Humidity
fields = ('id', 'value')
class TemperatureSerializer(serializers.ModelSerializer):
class Meta:
model = Temperature
fields = ('id', 'value', 'isFarenheit')
And this is the views.py:
from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Humidity, Temperature
from .serializers import HumiditySerializer, TemperatureSerializer
class HumidityView(viewsets.ModelViewSet):
queryset = Humidity.objects.order_by('-id')[0]
serializer_class = HumiditySerializer
class TemperatureView(viewsets.ModelViewSet):
queryset = Temperature.objects.order_by('-id')[0]
serializer_class = TemperatureSerializer
This is the traceback of the error:
Traceback (most recent call last):
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\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 "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\iotSensors\urls.py", line 21, in <module>
path('', include('api.urls')),
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\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 "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\api\urls.py", line 6, in <module>
router.register('humidity', views.HumidityView)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 75, in register
basename = self.get_default_basename(viewset)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 162, in get_default_basename
return queryset.model._meta.object_name.lower()
AttributeError: 'Humidity' object has no attribute 'model'
This error is only thrown when I change in the views.py from Humidity.objects.all() to Humidity.objects.order_by('-id')[0] and the same with temperature.
How do I return the last object saved?
Since you don't have time or date fields in your model, you may retrieve the latest object only through id.
Humidity.objects.all().order_by('-id')[:1]
-id retrieves the objects in the reverse order.
Since QueryDict object of django is lazily loaded, this will only retrieve the latest value.
You can use the last function to retrieve the latest object
Humidity.objects.all().latest()
or just retrieve the object with the latest id by
Humidity.objects.latest('id')
# To get last object or record
Humidity.objects.last()

AttributeError when I import model from another app

I don't know why but I got an error: AttributeError: module 'downloads.models' has no attribute 'AbstractDownload' in this place: class Download(models_downloads.AbstractDownload):
In download app I have already AbstractDownload class
Here is my model from products
products/models.py
from downloads import models as models_downloads
class Download(models_downloads.AbstractDownload):
product = models.ForeignKey('products.Product', related_name='downloads')
file = FilerFileField(related_name="file_products_download")
Here is downloads models
downloads/models.py
class AbstractDownload(models.Model):
title = models.CharField(max_length=500)
subtitle = models.CharField(max_length=1000, blank=True)
file = FilerFileField(related_name="file_abstract_download")
order = models.PositiveIntegerField(default=0)
class Meta:
abstract = True
def __str__(self):
return self.title
Traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/path/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/path/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute
django.setup()
File "/path/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/path/venv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/path/venv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/path/venv/lib/python3.5/importlib/__init__.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 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/path/www/downloads/models.py", line 6, in <module>
from products import models as products_models
File "/path/www/products/models.py", line 31, in <module>
class Download(models_downloads.AbstractDownload):
AttributeError: module 'downloads.models' has no attribute 'AbstractDownload'
You have a circular import. Your downloads/models.py has:
from products import models as products_models
But your products/models.py has
from downloads import models as models_downloads
You haven't shown how you use products_models, so we can't really say how to fix it. Here's a few suggestions:
Perhaps that import isn't necessary if you use a string for foreign keys, e.g. models.ForeignKey('downloads.ModelName')
Perhaps you could move AbstractDownload and Download so that they are in the same models, so that you don't need an import
If you use products_models inside a method, you could move the import inside the method. I would avoid this if possible.