Extending Zinnia Entry - python

i am currently working on a website where i want to use django-blog-zinnia with django-cms. I have to extend the entry by a foreign key to another so i followed the documentation on the zinnia website.
I wrote the zinnia_extra/models.py:
from django.db import models
from zinnia.models_bases.entry import AbstractEntry
class AssociationBlog(AbstractEntry):
association = models.ForeignKey("associations.Association",
blank=True,
default=None,
null=True,
related_name='news')
def __str__(self):
return 'AssociationBlog %s' % self.title
class Meta(AbstractEntry.Meta):
abstract = True
Now i came to the south part wich was a painful lesson of underdocumentation. After several hours of reading several answers here i found out that setting up the south migration modules mean something like this:
SOUTH_MIGRATION_MODULES = {
'zinnia': 'zinnia_extra.migrations.zinnia',
}
After that i added
ZINNIA_ENTRY_BASE_MODEL = 'zinnia_extra.models.AssociationBlog'
and also i built a zinnia_extra/admin.py:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from zinnia.models.entry import Entry
from zinnia.admin.entry import EntryAdmin
class AssociationBlogAdmin(EntryAdmin):
fieldsets = ((_('Content'), {'fields': (
('title', 'status'), 'content', 'image', 'association')}),) + \
EntryAdmin.fieldsets[1:]
admin.site.unregister(Entry)
admin.site.register(Entry, AssociationBlogAdmin)
(which is like in the documentation)
to the settings.py. South works as expected with an resolved migration error that is actually unresolved. But i managed to get that. But my extra field is not in the Admin area. I searched around and found out that i have to add the extra to the INSTALLED_APPS, so they now look like that:
INSTALLED_APPS = (
... ,
'zinnia',
'cmsplugin_zinnia',
'zinnia_ckeditor',
'zinnia_extra'
)
which is actually also found in the documentation (http://docs.django-blog-zinnia.com/en/latest/how-to/extending_entry_model.html).
But now i get an error like this:
Unhandled exception in thread started by <function wrapper at 0x1082ad9b0>
Traceback (most recent call last):
File "/myproject/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/myproject/venv/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/__init__.py", line 4, in <module>
from zinnia.models.entry import Entry
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/entry.py", line 6, in <module>
class Entry(load_model_class(ENTRY_BASE_MODEL)):
File: "/myproject/venv/lib/python2.7/site-packages/zinnia/models_bases/__init__.py", line 20, in load_model_class
raise ImproperlyConfigured('%s cannot be imported' % model_path)
django.core.exceptions.ImproperlyConfigured: zinnia_extra.models.AssociationBlog cannot be imported
I've searched for several hours now, but i am at the end and don't know how to search for this error type. Can someone provide an tutorial on the current extension workflow or help me with this error?

It seems the problem is the importation of zinnia_extra model.
Could be possible you need to add this line:
from zinnia_extra.models import AssociationBlog
in some file ?
I'm not sure in wich file, but it seems Django can't import your created class.
Maybe you need to add this import to your admin.py or other file where Django uses AssociationBlog
Other idea that comes to my mind is:
Could be that you need to add the zinnia_extra path to Python Path ? Is it in the same path as your project or same path as zinnia app?

Related

Error from Tasks job when referencing a model that uses from django.contrib.auth.models import User

My blog.models is using:
from django.contrib.auth.models import User
That model is being called from my script which I run as a task every hour. Here's the error that I'm seeing:
Traceback (most recent call last):
File "/home/redinv/src/cron.py", line 8, in <module>
from blog.models import ImagePost, MyPost, ScheduledPost
File "/home/redinv/src/blog/models.py", line 3, in <module>
from django.contrib.auth.models import User
File "/usr/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/usr/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/usr/lib/python3.8/site-packages/django/db/models/base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 60, 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.
2020-06-25 00:50:25 -- Completed task, took 3.95 seconds, return code was 1.
In my settings file under INSTALLED_APPS =, I already have:
'django.contrib.auth',
This code is of course working locally on my machine and I'm trying to figure what's the issue here?
I tried running that script from two locations to see if there was an issue trying to find the import files:
/home/username/src
/home/username/src/blog
Same result for both.
Any assistance is appreciate it, I'm pretty new at python.
Thanks
If you want to run Django code from outside the context of a website, you need to initialize Django first. There are two ways to do that:
Run the setup function to set things up; this part of the Django docs explains how to do that
Change the code that you want to run in your task into a management command. This is a little more work, but I would recommend it as a better option in the long term.

Django imports are failing after nesting apps in an apps folder

Here is what I did:
I wrapped my 12 Django apps in an apps folder in my Django project.
I added sys.path.append(os.path.join(BASE_DIR, 'apps')) in settings.py (before INSTALLED_APPS declaration) sothat I don't need to specify the apps folder when importing my apps.
I changed every 12 apps.py files to set name = apps.myappname
INSTALLED_APPS are still defined with myappname (not apps.myappname)
Here is what I have so far:
Code works normally
Unit tests, when run app by app, 100% works for the 12 apps.
Unit tests, when run as a whole, at some point of execution, fail with errors like this one:
ImportError: Failed to import test module: apps.badges.tests
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/vagrant/fugo/fugoproj/apps/badges/tests.py", line 10, in <module>
from .factories import BadgeFactory
File "/vagrant/fugo/fugoproj/apps/badges/factories.py", line 6, in <module>
from .models import Badge
File "/vagrant/fugo/fugoproj/apps/badges/models.py", line 51, in <module>
models.Model):
File "/home/ubuntu/fenv/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class apps.badges.models.Badge doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Here is the badges/factories.py file in error:
from datetime import timedelta
import factory
from django.utils import timezone
from .models import Badge
# some code
On every test which fails, it seems related to the relative import for the model (from .models import SomeModel). If I replace this with from myappname.models import SomeModel, this solve the error.
Any idea on something wrong in my code? I'd like to keep my relative imports.
How to explain it does not fail when running tests app by app?
Thanks.

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured

I’m using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a Python script that uses Django models.
C:\Users\admin\trailers>python load_from_api.py
Traceback (most recent call last):
File "load_from_api.py", line 6, in <module>
from movies.models import Movie
File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
class Genre(models.Model):
File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
id = models.CharField(max_length=10, primary_key=True)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 55, in __getattr__
self._setup(name)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
here's the script:
#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
import django
django.setup()
import tmdbsimple as tmdb
from movies.models import Movie
#some code...
I can't really figure out what's wrong. Any help is appreciated!
I figured out how to run it without changing the script and that's by using
python manag.py shell
and then
exec(open('filename').read())
that seemed to work just fine.
I would recommend using Django Custom Management Commands - they are really simple to use, they use your settings, your environment, you can pass parameters and also you can write help strings so you can use --help
Then you just call it with ./manage.py my_custom_command
Or if you just want to run your script add this to the your script
project_path = '/home/to/your/trailers/project/src'
if project_path not in sys.path:
sys.path.append(project_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.common")
import django
django.setup()

Django 1.7 makemigrations - ValueError: Cannot serialize class

I'm running into an interesting issue with an upgrade from Django 1.6.11 to 1.7. It seems to be based on how I am currently splitting up files. Currently, model methods are stored in separate files from the models, due to the massive amount of methods.
For example it is split up as follows:
help
|_ modelmethods
| |_ __init__.py
| |_ thread_methods.py
|_ __init__.py
|_ models.py
The __init__.py in the help app folder looks like so:
""" __init__.py for help app."""
from help.modelmethods.thread_methods import *
And thread_methods.py looks like this:
"""Methods for the Thread model."""
from help.models import Thread
class ThreadMethods:
"""Adds methods on to the Thread model."""
def do_the_thing(self):
pass
Thread.__bases__ += (ThreadMethods,)
The error that I'm seeing from this is as follows:
Migrations for 'help':
0001_initial.py:
- Create model Thread
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 124, in handle
self.write_migration_files(changes)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
migration_string = writer.as_string()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 129, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 86, in serialize
arg_string, arg_imports = MigrationWriter.serialize(arg_value)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 245, in serialize
item_string, item_imports = cls.serialize(item)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 380, in serialize
raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
ValueError: Cannot serialize: <class help.modelmethods.thread_methods.ThreadMethods at 0x1105c3870>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing
I realize that it is attempting to serialize the class and choking on it. Is there a good way to fix this and keep the separation? Or would the only comparable way be to break up the models.py file into a models folder with the proper __init__.py setup and each file be dedicated to one model that also contains all the relevant methods (as well as making sure no circular imports were introduced).
I was unable to migrate because of a custom validator. My problem was that I have not read the manual properly, where it says:
If a class-based validator is used in the validators model field
option, you should make sure it is serializable by the migration
framework by adding deconstruct() and __eq__() methods.
Which points to the migrations-docs which explain why you need the deconstruct() and __eq__() and how to write them.
Should also work for other classes and not just for validators.
This can happen due to many reasons, in my case it was I set default=User.pk for user Which was causing the issue. My django version is 1.9
class Blog(models.Model):
title = models.CharField(max_length=200)
content = HTMLField()
pub_date = models.DateTimeField('date published', auto_now_add=True)
last_updated = models.DateTimeField('date published',default=timezone.now)
user = models.ForeignKey(User, default=User.pk)#wrong
user = models.ForeignKey(User, default=1)#correct, use any default value
featured = models.ImageField(upload_to = 'featured', blank=True)
You need to derive your method-models from object class, also try deriving Thread from ThreadMethods instead of adding it to the __bases__.
class ThreadMethods(object):
# ....

Django Help - Basic Setup and Basic Functionality

Done my due diligence and still having issues. Here is my goal. I'm using Django with Python to create a website with some custom coded features. The problem I'm having is this. I've tried these tutorials: http://matthewdaly.co.uk/blog/2013/12/28/django-blog-tutorial-the-next-generation-part-1/
http://ferretfarmer.net/2013/09/05/tutorial-real-time-chat-with-django-twisted-and-websockets-part-1/ (would prefer to use just django and no twisted but open to anything.
Next to last is: http://www.djangorocks.com/tutorials/how-to-create-a-basic-blog-in-django/starting-your-application.html for blogs
And finally: creating a company site with blog, news pasting, etc. Most of which I can get via models as i have done in the past.
I've made progress: But I'm stuck at this part. When I try to run python manage.py runserver i get a huge error like this:
ages\django\conf\__init__.py", line 113, in __i nit__
[shenk#LUCY2 mytest]$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python27\lib\site- packages\django\core\management\__init__.py", line
338, in execute_from_command_line
utility.execute()
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
190, in fetch_command
klass = load_command_class(app_name, subcommand)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
40, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "c:\Python27\lib\site- packages\django\core\management\commands\runserver.py",
line 14, in <module>
from django.db.migrations.executor import MigrationExecutor
File "c:\Python27\lib\site-packages\django\db\migrations\executor.py", line 6,
in <module>
from .loader import MigrationLoader
File "c:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10,
in <module>
from django.db.migrations.recorder import MigrationRecorder
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 9,
in <module>
class MigrationRecorder(object):
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 23
, in MigrationRecorder
class Migration(models.Model):
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 24
, in Migration
app = models.CharField(max_length=255)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
1081, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
161, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 48, in __ge
tattr__
self._setup(name)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 44, in _set
up
self._wrapped = Settings(settings_module)
File "c:\Python27\lib\site-pack
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be
empty.
Please excuse the formatting it is not cooperating 100%, working pretty good though.
Anyway I want to create a site with django and add on to it a bunch of hard coded basic modules which I can do. What I need help with as I believe I mentioned is why I cant do python manage.py runserver? Or the other question I had was the tutorials I found for blogs and such on Django were either out of date or did not work well. Please guide me towards the best way to create a company website with Django. For now I need basic skills similar to word press without and plugins (comments, blog, etc.) I can add more advanced functionality myself once this is working. The info on the Django Doc's only works like 20% of the time.
Any help would be appreciated, my preferred answer is a bit of an explanmation how to use it, as well as what could be causing my runserver issues.
Any response is much appreciated. I know this isn't the place, but send me a message on SO and perhaps we can work out payment in order to learn from you, get the base application done. After that I can write the other modules myself. (Yes, you'll be complicated and you can telecommute as I'm in PA outside Philly.
P.S. I'm an advanced C/C++ dev, a bit of C#, JS, Java, and mainly Python.
If you need any more info I can help. I'm great with python and even .NET MVC but django is a bit different so any guidance is appreciated.
Thanks in advance.
It says you've not configured the SECRET_KEY setting. You need to set the value of the SECRET_KEY variable in your_app_name/settings.py - if you used the command python manage.py startproject to create your Django project, it should have done this for you.
See here: https://docs.djangoproject.com/en/1.8/ref/settings/#secret-key
open settings.py
add
SECRET_KEY = "IWANTDJANGO4SUMREASON"
to the bottom
According to your error log, you've improperly configured your Django application. The SECRET_KEY setting must not be empty. Please check your settings.py which is loaded by manage.py and make sure the SECRET_KEY contains an appropriate value. That should get you somewhere further.
On the other hand, I would suggest reading the official documentation aswell as follow the official tutorial on how to get started. These are more often up-to-date and follow the official guidelines.

Categories