django and python ./manage.py makemigrations execution error - python

thats my code in modeles.py
from django.db import models
from django.utils import timezone
class Book(models.Model):
title = models.CharField(max_length = 200)
author = models.CharField(max_lenght = 200)
description = models.TextField()
publish_date = models.DateField(Default= timezone.now)
that is when i type ./manage.py makemigrations execution error
that is what i see in shh
still error there is no control space to know when i pointer to mouse to django it appears unresolved reference 'django' while i installed it pip install django==1.8 and i run every time sudo pip install --ignore-installed virtualenvwrapper because when i use workon bookstore-django it does not execute until i run sudo pip install --ignore-installed virtualenvwrapper i am too beginner in this field
(bookstore-django) bavlys-Mac:bookstore bavlymorcos$ ./manage.py makemigrations store
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bavlymorcos/Desktop/development/bookstore/store/models.py", line 6, in <module>
class Book(models.Model):
File "/Users/bavlymorcos/Desktop/development/bookstore/store/models.py", line 10, in Book
publish_date = models.DateField(Default=timezone.now)
File "/Users/bavlymorcos/.virtualenvs/bookstore-django/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1201, in __init__
super(DateField, self).__init__(verbose_name, name, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'Default'

The Charfield part should be CharField.
In /Users/bavlymorcos/Desktop/development/bookstore/store/models.py, line no. 6,
it should be
title = models.CharField(max_length = 200)
ie. F in field should be Capital. (CharField instead of Charfield)
Docs: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.CharField

I solved the problem thanks guys
the problem was in model.py I changed it to like that
from django.db import models
from django.utils import timezone
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
description = models.TextField()
publish_date = models.DateField(default=timezone.now)

Related

Using Django, how do I add a foreign key column that references the same table? [duplicate]

This question already has answers here:
Django self-referential foreign key
(4 answers)
Closed 6 years ago.
I want a table to include a foriegn key field to itself, and have tried the following code:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)
This produces the following error:
$ ./manage.py makemigrations eav
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
File "/usr/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/username/Documents/devel/python/project/eav/models.py", line 7, in <module>
class CollectionModel(models.Model):
File "/home/username/Documents/devel/python/project/eav/models.py", line 8, in CollectionModel
parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)
NameError: name 'CollectionModel' is not defined
How do I include a foriegn key to the same table as a field?
As per https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey:
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
The above code should be changed to:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey('self', on_delete=models.CASCADE)
You need to add the below line to your model's
parent = models.ForeignKey('self', blank=True, null=True)
So, your model looks like,
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey('self', blank=True, null=True)

AttributeError: 'module' object has no attribute 'commit_on_success'

I'm trying to use Django-nested-inlines application but it raises error. Here is a simple code:
MODELS.PY
class Language_Quiz(models.Model):
name = models.CharField(max_length=40)
language = models.OneToOneField(sfl_models.Language)
class Question(models.Model):
language_quiz = models.ForeignKey(Language_Quiz)
text = models.TextField()
class Answer(models.Model):
question = models.ForeignKey(Question,related_name='answers')
text = models.TextField()
correct = models.BooleanField()
ADMIN.PY
from django.contrib import admin
import models
from nested_inlines.admin import NestedModelAdmin, NestedTabularInline
class AnswerInline(NestedTabularInline):
model = models.Answer
class QuestionInline(NestedTabularInline):
model = models.Question
class LanguageQuizAdmin(NestedModelAdmin):
inlines = [QuestionInline]
admin.site.register(models.Language_Quiz,LanguageQuizAdmin)
admin.site.register(models.Answer)
admin.site.register(models.Question)
But when I run server or try to make migrations, the error is raised. I have no idea where is the problem. Where is the problem?
TRACEBACK
(venv) C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line
utility.execute()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\management\__init__.py", line 328, in execute
django.setup()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\contrib\admin\apps.py", line 22, in ready
self.module.autodiscover()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\utils\module_loading.py", line 74, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\language_tests\admin.py", line 3, in <module>
from nested_inlines.admin import NestedModelAdmin, NestedTabularInline
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\nested_inlines\admin.py", line 16, in <module>
class NestedModelAdmin(ModelAdmin):
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\nested_inlines\admin.py", line 131, in NestedModelAdmin
#transaction.commit_on_success
AttributeError: 'module' object has no attribute 'commit_on_success'
As Kapil Sachdev and karthikr commented, the problem is with compatibility. Django-nested-inlines has probably some issues working with Django 1.8+.
In my case, the solution was very simple. Download using pip Django-nested-inline (without 's' at the end of the 'inline') and just change import. I didn't even have to change the code.

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):
# ....

Extending Zinnia Entry

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?

Django for some reason doesn't want to import one particular model

I have a Django model where I'm importing a number of items:
from django.db import models
from mcif.models.import_profile import ImportProfile
from mcif.models.import_file import ImportFile
from mcif.models.import_bundle import ImportBundle
from mcif.models.customer import Customer
#from mcif.models.account_import import AccountImport
from mcif.models.csv_row import CSVRow
import csv, cStringIO
It works fine, but when I uncomment that line that's commented, I get this:
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/lib/pymodules/python2.6/django/core/management/commands/shell.py", line 18, in handle_noargs
loaded_models = get_models()
File "/usr/lib/pymodules/python2.6/django/db/models/loading.py", line 167, in get_models
self._populate()
File "/usr/lib/pymodules/python2.6/django/db/models/loading.py", line 64, in _populate
self.load_app(app_name)
File "/usr/lib/pymodules/python2.6/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/lib/pymodules/python2.6/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/jason/projects/mcifdjango/mcif/models/__init__.py", line 5, in <module>
from mcif.models.account_import import AccountImport
File "/home/jason/projects/mcifdjango/mcif/models/account_import.py", line 2, in <module>
from mcif.models.generic_import import GenericImport
File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 6, in <module>
from mcif.models.account_import import AccountImport
ImportError: cannot import name AccountImport
Why doesn't Django like this one particular file?
(I can load AccountImport by itself on the console just fine.)
Also, here's AccountImport if it helps to see it:
from django.db import models
from mcif.models.generic_import import GenericImport
class AccountImport(models.Model):
id = models.BigIntegerField(primary_key=True)
generic_import = models.ForeignKey(GenericImport)
is_entirely_international = models.IntegerField()
is_queued = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
class Meta:
db_table = u'account_import'
app_name = 'mcif'
And GenericImport:
from django.db import models
from mcif.models.import_profile import ImportProfile
from mcif.models.import_file import ImportFile
from mcif.models.import_bundle import ImportBundle
from mcif.models.customer import Customer
from mcif.models.csv_row import CSVRow
import csv, cStringIO
class GenericImport(models.Model):
class Meta:
db_table = u'generic_import'
app_name = 'mcif'
id = models.BigIntegerField(primary_key=True)
import_profile = models.ForeignKey(ImportProfile)
import_file = models.ForeignKey(ImportFile)
notes = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
active = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
unsavable_rows = models.TextField()
import_bundle = models.ForeignKey(ImportBundle)
is_queued = models.IntegerField()
#classmethod
def last(cls):
all = GenericImport.objects.all()
return all[len(all) - 1]
def process(self):
for line in self.import_file.file.split("\n")[:30]:
f = cStringIO.StringIO(line)
row = CSVRow()
row.array = next(csv.reader(f))
row.generic_import = self
row.process()
f.close()
def specific_import(self):
for model_name in ['TransactionImport', 'AccountImport']:
specific_imports = eval(model_name + '.objects.filter(generic_import__pk=5)')
if len(specific_imports) > 0:
return specific_imports[0]
return False
You have a circular import - mcif.models.generic_import and mcif.models.account_import are trying to import each other.
Remember that Python is not Java, and is quite happy to have multiple classes in a single file, especially if they're closely related like these two seem to be. Put them both in a single mcif.models file.
That is a circular model dependency.
File "/home/jason/projects/mcifdjango/mcif/models/__init__.py", line 5, in <module>
from mcif.models.account_import import AccountImport
File "/home/jason/projects/mcifdjango/mcif/models/account_import.py", line 2, in <module>
from mcif.models.generic_import import GenericImport
File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 6, in <module>
from mcif.models.account_import import AccountImport
ImportError: cannot import name AccountImport
If you really need those models separated, have a look at http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.ForeignKey for a solution. Instead of importing the model, you can refer to it with a string.
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
Will use the Manufacturer model from the production module as target of the foreignkey.
It looks like you have a circular import there.
File "/home/jason/projects/mcifdjango/mcif/models/__init__.py", line 5, in <module>
from mcif.models.account_import import AccountImport
File "/home/jason/projects/mcifdjango/mcif/models/account_import.py", line 2, in <module>
from mcif.models.generic_import import GenericImport
File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 6, in <module>
from mcif.models.account_import import AccountImport
Your __init__.py imports AccountImport which imports GenericImport which then again imports AccountImport, though I'm not sure how importing it would work at all, honestly.
Does your GenericImport really need to import AccountImport? Seems like broken hierarchy.
edit: (for the updates)
def specific_import(self):
for model_name in ['TransactionImport', 'AccountImport']:
specific_imports = eval(model_name + '.objects.filter(generic_import__pk=5)')
if len(specific_imports) > 0:
return specific_imports[0]
return False
The eval line reeks of bad practice. There is certainly a better pattern here to use than this. Your generic classes should not have any knowledge or reliance on your specific implementations, not to mention eval really has almost no place in real code.

Categories