So when I create a model instance using the CLI, it works.
The model:
class Post(models.Model):
title = models.CharField(max_length=100)
cover = models.ImageField(upload_to='images/')
description = models.TextField(blank=True)
def __str__(self):
return self.title
Then I did:
$ python manage.py shell
>>>from blog.models import Post
>>>filename = 'images/s.png'
>>>Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')
And it worked, it showed up on the page that I'm displaying these models at.
However, when I take this same code and put it in a file, portfolio_sync.py, it doesn't work.
from blog.models import Post
filename = 'images/s.png'
Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')
I get this error:
Traceback (most recent call last):
File "portolio_sync.py", line 1, in <module>
from models import Post
File "/Users/rfrigo/dev/ryanfrigo/blog/models.py", line 4, in <module>
class Post(models.Model):
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
self._setup(name)
File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
How can I fix this, and create a model instance in a .py file? (Because I need to loop through a bunch of file names).
Thanks for your help!!
you have to run this script in shell
for executing this script in shell, open terminal and do like this:
python manage.py shell < myscriptname.py
Related
I want to add info in database using django-seed.
seed.py
from django_seed import Seed
from models import Employee
seeder = Seed.seeder()
seeder.add_entity(Employee, 5)
inserted_pks = seeder.execute()
When I try to start command: python3 seed.py
I've got this error:
Traceback (most recent call last):
File "seed.py", line 2, in <module>
from models import Employee
File "/home/kaucap/test/myproject/app_worker/models.py", line 4, in <module>
class Employee(models.Model):
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
self.check_apps_ready()
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready
settings.INSTALLED_APPS
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__
self._setup(name)
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Can anyone explain why I have this error and how I can fix it?
python3 seed.py started python without Django settings.
if you are want to start seed.py in Django "environment",
in your django-pproject folder:
python3 manage.py shell
Django shell starts, and in shell:
import seed.py
If you see the same error - you have not created any Django project yet.
I am building a fully open source testrunner for my needs but I am running into some problems. the test runner parses a yaml file for a set of scripts in various paths and executed the scripts and uses a lib that i will be creating to return the outcome. right now i have a simple ping script that im working to get running and testing as i progress but i am getting a lot of errors. the errors are below and all the source code is also shown below the errors.
The github repo for this is here. feel free to pull it in and test the issues i am seeing.
https://github.com/castaway2000/testrunner
The issue:
I am trying to use the testrunner i built to parse a yaml file for paths to scripts i am writing for projects im using.
For example if want to use a group of certain tests on a target, i can make a yaml file for each set of the types of tests.
There is a certain problem I am seeing with this however, the relative path and exact path of the files are not able to use the django libraries, cause its unable to find the path of the libraries unless its running from the top level of the django app (ie. ./ping_google.py vs ./testcases/ping_google.py)
but on top of that, the django app says is not running when the independent libraries are referencing models.py and admin.py cant import models from the same directory. I need help fixing and understanding this issue.
Here is the rundown(stacktrace):
Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
File "ping_google.py", line 1, in <module>
from testrunnerlib.test import HostInterface
File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
from testrunner.models import Host, TestSuite
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
class Host(models.Model):
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
after i put import django and django.setup() in the django settings file the above error goes away but i get the following error:
Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
File "ping_google.py", line 1, in <module>
from testrunnerlib.test import HostInterface
File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
from testrunner.models import Host, TestSuite
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
class Host(models.Model):
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 6, in Host
ip_address = models.CharField(max_length=16)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1043, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/xwing/PycharmProjects/testrunner/testrunner/settings.py", line 133, in <module>
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
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/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/xwing/PycharmProjects/testrunner/testrunner/admin.py", line 3, in <module>
from testrunner.models import Host, TestSuite
ImportError: cannot import name 'Host'
Fixing this will help with testing the rest of the build out scenarios for the testrunner but i will still need advice on the relative path and environment python needs to use to know where to look for these libraries. if possible i can put the libs in the root python directory so the libs are irrelevant to the problem.
problem file:
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes
from ping3 import ping
def pinger(host):
result = Outcomes()
try:
ping_google = ping(host)
print(ping_google)
if ping_google:
return result.passed()
msg = 'ping had an issue, the following is all we know %s' % ping_google
return result.failed(msg)
except Exception as e:
return result.aborted(exception=e)
if __name__ == '__main__':
pinger(HostInterface().target)
only lib with django imports:
import yaml
import subprocess
from testrunner.models import Host, TestSuite
class HostInterface(object):
def __init__(self):
self._target = 'not set'
#property
def target(self):
return self._target
#target.setter
def target(self, value):
print("setter of target called", value)
self._target = value
#target.deleter
def target(self):
print("deleter of target called")
del self._target
def host(self):
out = Host.objects.get(id=self.target).name
return out
class YamlInterface:
def __init__(self, yamlfile):
self.file = yamlfile
def handle_yaml(self):
data = TestSuite.objects.get(id=self.file)
yamldata = yaml.safe_load(data.text)
for i in yamldata['testsuite']:
status = subprocess.call('python3 %s' % i, shell=True)
print(status)
def run_tests(host, yaml):
h_interface = HostInterface()
h_interface.target = host
h_interface.host()
yaml = YamlInterface(yaml)
yaml.handle_yaml()
the models:
from __future__ import unicode_literals
from django.db import models
class Host(models.Model):
ip_address = models.CharField(max_length=16)
port = models.IntegerField()
name = models.CharField(max_length=256)
class TestSuite(models.Model):
name = models.CharField(max_length=256)
text = models.TextField()
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s" % self.name
admin.py
from django.contrib import admin
from django import forms
from testrunner.models import Host, TestSuite
class HostAdmin(admin.ModelAdmin):
list_display = ['name']
fields = ('name', 'ip_address', 'port')
def __str__(self):
return '%s' % self.name
pass
admin.site.register(Host, HostAdmin)
class TestSuiteAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(TestSuiteAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'text':
formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
return formfield
admin.site.register(TestSuite, TestSuiteAdmin)
You need to make a Django Management Command. This will let you create scripts that will allow you to use all of Django's features.
And you would run this command as python3 manage.py ping_google
To create a management command,
In your apps folder, create a module called management (make a folder called management and place init.py file in it)
Inside the management folder, create a commands module (folder and init.py file)
Inside the commands folder create your ping_google.py file.
Commands are written like this,
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Desc of your command'
def handle(self, *args, **options):
# Your logic goes here
You can read more on custom django commands here
Custom management command, oauth.py, needs a model from another module. When I include "from appname.authentication.models import Contact" I get "AttributeError: 'module' object has no attribute 'models'." - Im stuck on django 1.6 until I able to build an test suite to help with the upgrade.
How do I correctly import Contact?
Other notable SO answers:
Circular Import
Import Settings
Each directory other than /app has an __init__.py . /app is in sys.path/ django directory, /app:
util
-management
--commands
---oauth.py
appname
-authentication
--models.py
extouth.py
extoauth.py is standalone script with the same import and works, but only in manage.py shell. The custom management command will be better.
oauth.py:
import sys
from optparse import make_option
from provider.oauth2.models import Client
from appname.authentication.models import Contact
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Creates OAUTH user and gets access token.'
option_list = BaseCommand.option_list + (
make_option('--create-client',
dest='create_client',
help='''Returns tuple of <id,secret>...'''),
make_option('--get-access-token',
dest='get_access_token',
help='''Returns time limited access token...'''),
)
def handle(self, *args, **options):
if options['create_client']:
return self.create_client(options['create_client'])
elif options['get_access_token']:
self.get_access_token()
def create_client(self, user):
return user
def get_access_token(self):
pass
Console out:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/app/waapiutil/management/commands/oauth.py", line 4, in <module>
from wowza.authentication.models import Contact
File "/app/wowza/authentication/models.py", line 80, in <module>
class
SalesforceModel(with_metaclass(salesforce.models.SalesforceModelBase, models.Model)):
AttributeError: 'module' object has no attribute 'models'
hypo - settings is not getting imported
So my settings must be getting set just as they do with the manage.py shell usage because if I include at the top of my file:
from django.conf import settings
settings.configure()
I get:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/app/waapiutil/management/commands/oauth.py", line 2, in <module>
settings.configure()
File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 89, in configure
raise RuntimeError('Settings already configured.')
RuntimeError: Settings already configured.
hypo - deeper syntax error (that should have broken production anyway)
searching for occurrences of models.model in my app files yields four results, each has the correct capitalization of models.Model.
hypo - Contact is already imported
When I comment out the import and run the command i get:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/app/waapiutil/management/commands/oauth.py", line 23, in handle
return self.create_client(options['create_client'])
File "/app/waapiutil/management/commands/oauth.py", line 32, in create_client
c = Client(user=Contact.objects.get_by_email(e), name=n,
NameError: global name 'Contact' is not defined
Snippets from authentication/models.py for hynekcer's comment
# Core Django imports
from django.db import models
from django.core.validators import MinLengthValidator
from django.utils.six import with_metaclass
# Third-party imports
import pycountry
from rest_framework.compat import oauth2_provider
import salesforce
from salesforce import fields
from salesforce.backend import manager
...
class SalesforceManager(manager.SalesforceManager):
"""
Override the default Salesforce manager so we can get some proper REST framework exceptions
"""
def get(self, *args, **kwargs):
try:
result = self.get_queryset().get(*args, **kwargs)
except self.model.MultipleObjectsReturned:
raise MultipleUniqueRecords()
except Exception as e:
logger.warning("SalesForce exception %s", str(e))
raise NoRecord()
return result
class SalesforceModel(with_metaclass(salesforce.models.SalesforceModelBase, models.Model)):
"""
Abstract model class for Salesforce objects.
"""
_base_manager = objects = SalesforceManager()
_salesforce_object = True
class Meta:
managed = False
abstract = True
Id = fields.SalesforceAutoField(primary_key=True)
def clean_fields(self, *args, **kwargs):
# Override the default clean_fields method so we can catch validation exceptions
try:
super(SalesforceModel, self).clean_fields(*args, **kwargs)
except Exception as validation_exception:
detail = ''
for field, message in validation_exception.error_dict.items():
detail += field + ': ' + message[0].messages[0]
raise ValidationError(detail)
def save(self, *args, **kwargs):
# Override the default save method so we can remove fields that Salesforce manages
if self._meta.model_name in ['contact', 'account', 'license', 'sslcertificate']:
if not self.Id:
for field in self._meta.fields:
if field.attname == 'created_date' or field.attname == 'certificate_id':
self._meta.fields.remove(field)
else:
update_fields = self._meta.get_all_field_names()
remove_list = []
if self._meta.model_name == 'contact':
remove_list = ['created_date', 'accesstoken', 'refreshtoken', 'oauth2_client', 'grant', 'Id', 'entitlement_plan']
elif self._meta.model_name == 'account':
remove_list = ['created_date', 'account', 'Id']
elif self._meta.model_name == 'license':
remove_list = ['created_date', 'Id']
elif self._meta.model_name == 'sslcertificate':
remove_list = ['certificate_id', 'created_date', 'Id']
for remove_field in remove_list:
if remove_field in update_fields:
update_fields.remove(remove_field)
kwargs['update_fields'] = update_fields
# Retry five times if there's a SalesforceError
delay = 1
for retry in range(5):
try:
super(SalesforceModel, self).save(*args, **kwargs)
break
except Exception as e:
logger.error("Saving {0} resulted in an error {1}, retry {2}".format(str(self),str(e),retry))
if retry < 4 and "SERVER_UNAVAILABLE" in str(e):
time.sleep(delay)
delay *= 2
else:
(This is a comment requiring much place, not the answer yet.)
I thought my eyes deceiving when I saw a line from my database backend in your application code, maybe also with a concrete model in the same module. I see that your pasted code is based on an older django-salesforce 0.5.x code. OK, hopefully you use also the package 0.5.x. It probably can not work with the current django-salesforce 0.6 or nobody should expect it
The most safe style is to use the public API. A more fragile style is to use also undocumented features. The most fragile is to copy-paste code from the core of other package and to forget that you started to use a new version. You must have a sufficiently serious reason and enough time if you do such things. (I did it six times for every Django version because the django-salesforce backend is interesting enough for me, but I don't reccomend it to you.)
You can write simply:
class MySalesforceModel(salesforce.models.SalesforceModel):
def ... # your custom method
class Meta:
managed = False
abstract = True
The advantage is that this will use the right current SalesforceModel even with the next version of Django and django-salesforce.
If you really need to customize a backend, please comply a sane separation of the backend and application code to different modules so that the backend can be imported without importing any concrete model. Otherwise you can easy get ugly dependencies. Also a nonempty 'init.py` can cause sily dependencies
You need no hypothesis ("hypo") for such simple things if you have the complete source code. You can simply log (print) that information e.g. put import sys; print("settings imported", "my_project.settings" in sys.modules) or verify that settins are correctly configured - put temporarily a line just before a problematic place: from django.conf import settings; print(settings.INSTALLED_APPS) # any valid name
You should check syntax errors before asking a help. It can be done easily for any specific Python version for a tree of subdirectories e.g. by python2.7 -m compileall $(pwd)
It is very insane to use a general handling except Exception: especially while you are debugging. Imagine that the code between try...except will raise an ImportError and you swallow it.
It can be easier to solve dependencies by refactoring the code than to maintain the fragile code later. Imagine that you import inside a function and you get a strange ImportError message from your friend only sometimes if the module is imported from a thread only in Apache, but it succeeds if you import it from the main thread. Explicit import is favoured.
I have two classes which import each other:
profile/models.py
class Company(models.Model):
name = ...
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from action.models import CompanyAction
action = models.ForeignKey(CompanyAction)
action/models.py
from profile.models import Company
class CompanyAction(models.Model):
company = models.ForeignKey(Company, null = True, blank = True)
The circular import works when the Django app is executed on the server or when I call view functions in the shell. However, when I import one of the classes, Django command will fail with an error (see Traceback below).
Why is that the case and only causing a problem in the command method?
How can I avoid the error? I have tried a lazy import of the CompanyAction class, but it led to the same error message.
not working alternative:
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from django.db.models import get_model
_model = get_model('action', 'CompanyAction')
action = models.ForeignKey(_model)
Interestingly, the variable _model is empty if I execute my command function and the classes are imported. When I load ./manage.py shell, the variable contains the correct class name. Why is that the case?
Traceback
(virtual-env)PC:neurix$ python manage.py close_action
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Development/project/apps/action/management/commands/close_action.py", line 2, in <module>
from action.models import CompanyAction
File "/Users/Development/project/apps/action/models.py", line 26, in <module>
from profile.models import Company
File "/Users/Development/apps/profile/models.py", line 436, in <module>
class CompanyReview(models.Model):
File "/Users/Development/project/apps/profile/models.py", line 446, in CompanyReview
action = models.ForeignKey(_model)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/db/models/fields/related.py", line 993, in __init__
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
Django has a system for stopping circular imports on foreign keys detailed here: https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
You would want to do something like:
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
action = models.ForeignKey('action.CompanyAction')
class CompanyAction(models.Model):
company = models.ForeignKey('profile.Company', null = True, blank = True)
Preface: I was writing my own Page app that used MPTT and a custom page model. This was working for me, but FlatPages is more refined than my custom Page Model and so I'm leaning toward just extending it.
from django.db import models
from django.contrib.flatpages.models import FlatPage
from mptt.models import MPTTModel
class ExtendedFlatPage(FlatPage, MPTTModel):
parent = models.ForeignKey('ExtendedFlatPage', null=True, blank=True, default=None, related_name="children", help_text="Hierarchical parent page (if any)")
class Meta:
ordering = ['flatpages__url']
order_with_respect_to = 'parent'
verbose_name = 'page'
verbose_name_plural = 'pages'
class MPTTMeta:
left_attr = 'mptt_left'
right_attr = 'mptt_right'
level_attr = 'mptt_level'
order_insertion_by = ['title']
def __unicode__(self):
return self.url
This almost works, except throws an error when I go to run python manage.py syncdb
Error:
iMac:cms colab$ python manage.py syncdb
Creating tables ...
Creating table my_flatpages_extendedflatpage
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/commands/syncdb.py", line 101, in handle_noargs
cursor.execute(statement)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build/bdist.macosx-10.6-intel/egg/MySQLdb/cursors.py", line 174, in execute
File "build/bdist.macosx-10.6-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
django.db.utils.DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 2")
If anyone could point me in the right direction, I would greatly appreciate it. Thanks!
replace
class ExtendedFlatPage(FlatPage, MPTTModel):
with
class ExtendedFlatPage(MPTTModel, FlatPage):
This will allow MPTTModel class to override FlatPage attributes and methods.
#comment
It appears that something (an attribute, method) in FlatPage model overrides something in MPTTModel cousing this error.
order of classes you import from is important. here's an example:
class A:
attribute = 1
class B:
attribute = 2
class C(A,B):
pass
class C attribute value will be 1.