I have a new Python project, with a models.py file that looks like this:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
class Metric(models.Model):
users = models.ManyToManyField(User, through = 'Vote')
name = models.CharField(max_length = 255)
class Vote(models.Model):
metric = models.ForeignKey(Metric, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete = models.CASCADE)
rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
email = models.EmailField
def __str__(self):
return str(self.rating)
and an admin.py file like this:
from django.contrib import admin
from models import Metric, Vote
admin.site.register(Metric)
admin.site.register(Vote)
When running this with Python 2.7.5, launching the app works fine. When I try to run it using Python 3.5.1, I get the error ImportError: No module named 'models', with this backtrace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103bd2b70>
Traceback (most recent call last):
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/sashacooper/pyenv/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 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/Users/sashacooper/Desktop/pogroms/crockerometer2/crockerometer/admin.py", line 2, in <module>
from models import Metric, Vote
I've tried adding from __future__ import absolute_import to the start of the admin.py file per similarly titled Stack Overflow posts but it didn't change the error. What's causing it?
In Python 3 you must tell it when you are using relative imports:
from .models import ...
try from .models import Metric, Vote in your admin.py
I have always used:
from myapp.models import ...
Rather than a relative import. Just my personal preference. Perhaps relative import makes more sense if it is the admin.py for myapp, but I still like the explicitness of having the app name in the import.
Related
I am using python3 in a virtual environment and have wagtail installed via pip. When I am trying to extend home model for home page. I get the error:-
ImportError: No module named 'wagtail.core'
Here is the code of models.py:-
from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
class HomePage(Page):
body = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('body', classname="full"),
]
Here is the error stack:-
*Unhandled exception in thread started by <function check_errors
<locals>.wrapper at 0x7f8a45e44400>
Traceback (most recent call last):
File "/project/venv/lib/python3.4/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs)
File "/project/venv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception()
File "/project/venv/lib/python3.4/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception)
File "/project/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb)
File "/project/venv/lib/python3.4/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs)
File "/project/venv/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS)
File "/project/venv/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models()
File "/project/venv/lib/python3.4/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name)
File "/project/venv/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/project/home/models.py", line 3, in <module> from wagtail.core.models import Page ImportError: No module named 'wagtail.core'*
I am following the basic tutorial for wagtail. Here is the link http://docs.wagtail.io/en/latest/getting_started/tutorial.html
Version of wagtail==1.13.1 and Django==1.11.10. Kindly point to right direction. Thanks in advance.
Edited.
You wrote import statements for wagtail 2.x.
Replace import statements with following statements which is for wagtail 1.13.1:
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
Kindly follow this link
http://docs.wagtail.io/en/v1.13.1/getting_started/tutorial.html
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.
from django.db import models
from django.contrib.gis.db import models
location = models.PointField(srid=4326,null=True,blank=True)
objects = models.GeoManager()
I am hosting my Django project on AWS server. I am unable to run the project because of the error I added below, but I implemented the same project in my Ubuntu system and it's working fine.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f527104b6a8> Traceback (most recent call last): File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/django_env/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 "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 10, in <module> class BusStop(models.Model): File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 17, in BusStop objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager'
Is it possible that you are running Django 2.0?
GeoManager has been removed.
A workaround that appears to function correctly as of Django 2.0:
Import in your models file:
from django.db.models import Manager as GeoManager
In your model class:
objects = GeoManager()
Now you should be able to do spatial lookups!
Credit to this django-cities pull request.
You could try:
from django.contrib.gis.db.models.manager import GeoManager
Also you'll want to avoid situations like this
from django.db import models
from django.contrib.gis.db import models
The problem is this, you've imported two models modules - which one does Python use when you try to use models.Whatever?
Try something like this:
from django.db import models
from django.contrib.gis.db import models as gis_models
Instead of GeoManager you can now just use Manager
from django.db.models.manager import Manager
I have GDAL (using homebrew) and SQLite installed. I would like to create a teacher with a PointField() which stores long and lat values, to know their location. Later I plan on adding the ability to search by distance using something like:
Teacher.objects.filter(location__distance_lte=(your_location,D(m=distance))).distance(your_location).order_by('distance')
models.py
from django.db import models
from django.contrib.gis.db import models as gis_models
from django.contrib.auth.models import User
class Teacher(models.Model):
user = models.ForeignKey(User, unique=True)
location = gis_models.PointField()
availability = models.BooleanField(default=False)
However, when I run the server, I get the following error:
Unhandled exception in thread started by <function
check_errors.<locals>.wrapper at 0x111c619d8>
Traceback (most recent call last):
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/utils/autoreload.py",
line 227, in wrapper
fn(*args, **kwargs)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/commands/runserver.py",
line 117, in inner_run
autoreload.raise_last_exception()
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/utils/autoreload.py",
line 250, in raise_last_exception
six.reraise(*_exception)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/utils/six.py",
line 685, in reraise
raise value.with_traceback(tb)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/utils/autoreload.py",
line 227, in wrapper
fn(*args, **kwargs)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/__init__.py",
line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/apps/registry.py",
line 108, in populate
app_config.import_models()
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/apps/config.py",
line 202, in import_models
self.models_module = import_module(models_module_name)
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/importlib/__init__.py",
line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/Users/gr/Desktop/PycharmProjects/DjangoWebsite/users/models.py",
line 2, in <module>
from django.contrib.gis.db import models as gis_models
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/db/models/__init__.py",
line 3, in <module>
from django.contrib.gis.db.models.aggregates import * # NOQA
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/db/models/aggregates.py",
line 1, in <module>
from django.contrib.gis.db.models.fields import ExtentField
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py",
line 3, in <module>
from django.contrib.gis import forms, gdal
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/forms/__init__.py",
line 3, in <module>
from .fields import ( # NOQA
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/forms/fields.py",
line 4, in <module>
from django.contrib.gis.geos import GEOSException, GEOSGeometry
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/geos/__init__.py",
line 18, in <module>
HAS_GEOS = geos_version_info()['version'] >= '3.3.0'
File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/contrib/gis/geos/libgeos.py",
line 196, in geos_version_info
raise GEOSException('Could not parse version info string "%s"' % ver)
django.contrib.gis.geos.error.GEOSException: Could not parse version info string "3.6.2-CAPI-1.10.2 4d2925d6"
This is a known issue, which has been fixed and will be rolled out in Django v1.11.5.
If you can't wait for 1.11.5 or don't want to run on the dev branch, you can go to a previous version of geos:
brew switch geos 3.6.1
In AdminForm I prevent the user from duplicating the records.
from django import forms
from django.contrib.auth.models import User
from apps.accounting_users.models import AccountingUser
from apps.marketing_users.models import MarketingUser
from apps.mgmt_users.models import ManagementUser
from apps.serv_mgrs_users.models import ServiceMgmtUser
from apps.serv_staff_users.models import ServiceStaffUser
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(
queryset=User.objects.exclude(
username__in=[record.user.username for record in AccountingUser.objects.all()] +
[record.user.username for record in MarketingUser.objects.all()] +
[record.user.username for record in ManagementUser.objects.all()] +
[record.user.username for record in ServiceMgmtUser.objects.all()] +
[record.user.username for record in ServiceStaffUser.objects.all()],
)
)
mgmt_users/models.py
from apps.commons.models import AbstractSBrandUser
class ManagementUser(AbstractSBrandUser):
pass
commons/models
class AbstractSBrandUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True)
mobile = models.CharField(max_length=15)
class Meta:
abstract = True
OSX 10.12.4 pytest is normal
Debian:Jessie is broken
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/buddy/siam-sbrand/portal/apps/mgmt_users/admin.py", line 3, in <module>
from apps.commons.forms import BaseDjangoAdminRoleForm
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 11, in <module>
class BaseDjangoAdminRoleForm(forms.ModelForm):
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 17, in BaseDjangoAdminRoleForm
[record.user.username for record in ServiceMgmtUser.objects.all()] +
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 1087, in _fetch_all
Question:
I had checked the syntax based on python3 already.
And I had checked the filter syntax of Django1.10 already.
python manage.py shell run fine. No error at all.
How can I use queryset in the AdminForm of the Django and pass the test?
Do I need to sacrify testing for this feature?
You can't use querysets like [record.user.username for record in AccountingUser.objects.all()] in your model form definition. Django tries to evaluate the queryset when the module is loaded. If the table has not been created yet, this will give an error.
You can fix the problem by setting the queryset in the __init__ method.
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.none())
def __init__(self, *args, **kwargs):
super(BaseDjangoAdminRoleForm, self).__init__(*args, **kwargs)
self.fields['user'].queryset = User.objects.exclude(...)
This has the advantage of evaluating the usernames every time the form is created - at the moment, they are only evaluated once when the server starts.