Django 1.10 path is on mount 'C:', start on mount 'D:' - python

I wanted to add additional fields to a many-to-many relationship and I created a intermediate model called Contact ( the goal is to implement a system that allows the user to follow other users and be followed too).
class Contact(models.Model):
user_from = models.ForeignKey(User,
related_name='rel_from_set')
user_to = models.ForeignKey(User,
related_name='rel_to_set')
created = models.DateTimeField(auto_now_add=True,
db_index=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return '{} follows {}'.format(self.user_from, self.user_to)
I am using the User model provided by Django (from django.contrib.auth.models) . As this model is not one I created if I want to add fields to it, I should (or at least, I think I should ) add them dinamically (with monkey-patch) . So at the end of the models.py file I added the following code:
User.add_to_class('following', models.ManyToManyField('self', through=Contact , related_name='followers', symmetrical=False))
But I runned the python manage.py makemigrations I got the following error :
Migrations for 'auth':
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\commands\makemigrations.py", line 192, in handle
self.write_migration_files(changes)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\managem
ent\commands\makemigrations.py", line 210, in write_migration_files
migration_string = os.path.relpath(writer.path)
File "C:\Program Files (x86)\Python35-32\lib\ntpath.py", line 574, in relpath
path_drive, start_drive))
ValueError: path is on mount 'C:', start on mount 'D:'
After a quick google search :
"os.relpath does give you a relative path between two directories.
The problem you are encountering is that, on Windows, a relative path doesn't even exist if the two directories are on different drives (which is exactly what the error message says). "
But what is the solution ?
I am using Windows 8 and Django 1.10.

You are running makemigrations from another drive (not from C: where django is installed).
There was a bug with makemigrations on Windows:
see this Django ticket,
and the commit that fixed the bug:
makemigrations crash when creating migrations on a separate drive than where Django is installed
So to fix this error you should:
move your Django project (your Python code) on C: drive
or update your Django version (to Django 1.11)

Related

Django multitenant migration raises KeyError: "prune"

So I've been working in a project for a while, and haven't really changed the models at all, and therefore haven't done any migrations. Now I needed to add two new fields and delete another one, which should be normally fine. I'm using django-tenants, so my command to run the migrations is ./manage.py migrate_schemas.
Now, whenever I run that, I get the error KeyError: "prune" (the full traceback is below) in what seems to be internal code of Django.
Now, afterwards I tried reverting my changes, so no new migration and running the comnad again, and got the same error. I also thought that maybe the database had gotten "dirty" at some point, so I tried migrating a clean database from scratch, with the same result. The migrations don't even get to start.
Has anyone ever encountered something similar?
The full traceback (I have simplified the paths)
[standard:public] === Starting migration
Traceback (most recent call last):
File ":directory/./manage.py", line 22, in <module>
main()
File ":directory/./manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "$venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "$/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "$venv/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 52, in handle
executor.run_migrations(tenants=[self.PUBLIC_SCHEMA_NAME])
File "$venv/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 11, in run_migrations
run_migrations(self.args, self.options, self.codename, self.PUBLIC_SCHEMA_NAME)
File "$venv/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 53, in run_migrations
MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)
File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "$venv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "$venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 188, in handle
if options["prune"]:
KeyError: 'prune'
It seems like version incompatibility.
prune option added to Django couple months ago (Jan 22, 2022)
If you want to use newer Django you have to patch django-tenants manually and add --prune argument
def add_arguments(self, parser):
parser.add_argument(
'--prune', action='store_true', dest='prune',
help='Delete nonexistent migrations from the django_migrations table.',
)
PS I couldn't find issue related to prune, so you may create new one ;)

Exception when migrating custom User in Django

I need to create a custom User for my app and followed exactly the example from the documentation with the AUTH_USER_MODEL = 'core.MyUser' in my settings.py. However, when I make a new database, delete all the migrations folders and run the python manage.py migrate again, it gives me the exception like this
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 173, in handle
migration_name=self.migration_name,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 47, in changes
changes = self._detect_changes(convert_apps, graph)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 132, in _detect_changes
self.old_apps = self.from_state.concrete_apps
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 180, in concrete_apps
self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 242, in __init__
self.render_multiple(list(models.values()) + self.real_models)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 277, in render_multiple
model.render(self)
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/migrations/state.py", line 559, in render
body,
File "/Users/bubuzzz/Projects/python/apps/lib/python2.7/site-packages/django/db/models/base.py", line 153, in __new__
raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
TypeError: Customer cannot proxy the swapped model 'core.MyUser'.
I am not sure why there is a migrations script for the customer there, since in my app, I used to have the Customer model as well, though I deleted it already.
Then, I created a new django project to test and try to run the migration. Surprisingly, I also see those customer migration steps, but it run successfully.
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_customer... OK
Applying auth.0010_delete_customer... OK
Applying sessions.0001_initial... OK
In short, how can I create the custom User in Django 1.10 ? Example code can be viewed in here https://github.com/bubuzzz/django-customer-swap-exception
You should not delete your migration folder. If you do that, django won't make migrations for you. Create migrations folder in your core app, create an empty __init__.py file inside it, remove your db.sqlite3 file, run ./manage.py makemigrations, and then migrate should work perfectly.
Mehdi Pourfar's answer is correct.If you want to know more details
By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.
Tell django which app you want to make migrations all fix your problem.It will auto create a folder call migrations keep your model's record.
python manage.py makemigrations core

Django syncdb works in SQLite, failing in MySQL

I'm a newbie to MySQL, and haven't used Django for anything in production. I've been doing development under Windows 7 with SQLite, and am trying to move the code to a Linux server running MySQL.
When I ran syncdb, it created the first three tables then threw an error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/base.py", line 415, in handle
return self.handle_noargs(**options)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/core/management/commands/syncdb.py", line 96, in handle_noargs
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
File "/home/gsdemo01/project_file/lib/python3.3/site-packages/django/db/backends/creation.py", line 83, in sql_create_model
model, f, known_models, style)
TypeError: sql_for_inline_foreign_key_references() takes 4 positional arguments but 5 were given
The model immediately after the last one created is a Metaclass, followed by a class that inherits from it:
class Location(models.Model):
# con = models.ForeignKey(Convention)
name = models.CharField(max_length=40)
scheduler = models.ForeignKey(GCUser, blank=True, null=True)
class Meta:
abstract = True
def __str__(self):
return self.name
class Room(Location):
tag = models.CharField(max_length=10)
capacity = models.PositiveSmallIntegerField(default=100)
This works fine with SQLite, so it seems like it has to be either a problem with the python connector package or with MySQL itself.
Thanks in advance for any help.
Update:
Through trial and error I've determined that the issue is definitely with the Foreign Key field. If I comment that out the table is created correctly. As far as I can tell the modification suggested by Yogesh matches what we already have in the code, so if anyone has any other suggestions I'd love to hear them.
If you using these virsions Python3.3 Django1.6 use MySql official middleware mysql-connector-python-1.1.4-py3.3.
The solution:
find: creation.py within your site-packages and Modification method: sql_for_inline_foreign_key_references is: you can only modify the method parameters
def sql_for_inline_foreign_key_references (self, model, field, known_models, style):
This is not a good solution,this is alternate for remove error.
I'm posting the solution here for the benefit of future users who run into this. It took many hours on the part of my partner to ferret this out.
The simple part of the solution is to edit creation.py to change
def sql_for_inline_foreign_key_references (self, model, field, known_models, style):
to
def sql_for_inline_foreign_key_references (self, *args):
There's a routine with the same name and almost the same syntax in site-packages/django/db/backends/creation.py, but you want the one in site-packages/django/db/backends/mysql/creation.py.
You're not done yet, though, because the module gets copied to site-packages/mysql/connector/django/creation.py, and that doesn't happen automatically on edit, so you'll need to copy it over manually. I deleted the .pyc file for good measure, but that "shouldn't" have been necessary.
Of course, none of this should have been necessary...
For Mac users using MacOSX 10.9 (aka Mavericks) or up, this solution works perfectly, but be sure you're going to the right place if you're using python3 to edit the creation.py file from the mysql.connector:
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/mysql/connector/django/creation.py
FYI:
Environment: Python3 / Mysql-connector-1.1.4 / Django-1.6.1

django.contrib.comments.moderation.AlreadyModerated error in zinnia django

I had a django app in which i am using django-zinnia-blog for my blog functionality.
Issue One
And now i updated zinnia with latest github version and i am getting the below wierd error
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x941554c>>
Traceback (most recent call last):
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors
self._populate()
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 72, in _populate
self.load_app(app_name, True)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/user/name/virtualenvironment/apps/proname/proname/apps/zinnia/models/__init__.py", line 19, in <module>
moderator.register(Entry, EntryCommentModerator)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/contrib/comments/moderation.py", line 305, in register
raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.module_name)
django.contrib.comments.moderation.AlreadyModerated: The model 'entry' is already being moderated
django version -- 1.5.3
So why it is displaying AlreadyModerated error when trying to update the zinnia witj latest version ?
Issue Two
Below are my specs/setings
settings.py
ZINNIA_ENTRY_BASE_MODEL = 'proname.apps.app_name.models.EntryBase'
ZINNIA_SAVE_PING_DIRECTORIES = False
ZINNIA_PING_EXTERNAL_URLS = False
Actually i am trying to extend the Entry model as below
from zinnia.models_bases.entry import AbstractEntry
class EntryBase(AbstractEntry):
pass
class Meta(AbstractEntry.Meta):
abstract = True
verbose_name_plural = _("Entry")
verbose_name_plural = _("Entries")
def __unicode__(self):
return u'Entry %s' % self.title
django version -- 1.4.5
When i used above django version i am getting an extra error along with above one
raise ImproperlyConfigured('%s cannot be imported' % model_path)
django.core.exceptions.ImproperlyConfigured: zinnia.models_bases.entry.AbstractEntry cannot be imported
So can anyone please let me know to solve the above issues like
AlreadyModerated when updating to latest github zinnia code
Trying to extend the Entry model ?
and made the zinnia work correctly ?
I had the same problem and I figure out the problem changing version of zinnia to 0.14.3
Zinnia 0.15 only works with django 1.7
Use v0.14.3 instead.
(https://github.com/Fantomas42/django-blog-zinnia/issues/388)
I came across this issue too. The way I was able to fix it was to link back to the model_bases folder in the original zinnia package. In my site's 'zinnia' folder (where the updated South migrations are stored):
$ ln -sf <python-path>/lib/python2.7/site-packages/zinnia/models_bases .

Set new `path` value for ImageField

I have the following situation. Project files was stored in ~/django-apps/app-old/app. For some reasons I move files to ~/django-apps/app . Application have some images, stored with use of ImageField. In database images have paths like so:
~/django-apps/app-old/app/media/images/blabla.jpeg
So, I need to fix this paths in database to look like this:
~django-apps/app/media/images/blabla.jpeg
I try to write management command for to do this:
from django.core.management.base import BaseCommand, CommandError
from books.models import Book
import string
class Command(BaseCommand):
help = ''
def handle(self, *args, **options):
books = Book.objects.all()
total = len(books)
curr = 1
for book in books:
print "%d/%d" % (curr, total)
if book.cover_url != "":
book.cover_url.path = string.replace(book.cover_url.path, "app-old/", "")
book.save()
curr+=1
By using this command I get following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/var/www/dizpers/data/django-apps/app/books/management/commands/fix-covers-path.py", line 23, in handle
book.cover_url.path = string.replace(book.cover_url.path, "bparser-old/", "")
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/files.py", line 65, in _get_path
return self.storage.path(self.name)
File "/usr/local/lib/python2.6/dist-packages/django/core/files/storage.py", line 234, in path
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
django.core.exceptions.SuspiciousOperation: Attempted access to '/var/www/dizpers/data/django-apps/app-old/app/media/covers/a3d9545d3a17bb68a91749019c95357d.jpeg' denied.
Why I get this error message? How I can fix image's path?
UPD1
My model contain ImageField like this:
cover_url = models.ImageField(upload_to=os.path.join(MEDIA_ROOT, "covers"), null=True, default=None)
UPD2
Path property is readonly
This should work
for book in books:
print "%d/%d" % (curr, total)
if book.cover_url != "":
new_path = string.replace(book.cover_url.path, "app-old/", "")
book.cover_url = new_path
book.save()
curr+=1
You get this message because the default file system storage prevents usage of absolute path for security reasons.
If you really want to use an absolute path
django-documents forces absolute paths for security reasons, this is how:
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location=UPLOAD_TO)
class Document(models.Model):
file = models.FileField(storage=fs, upload_to=UPLOAD_TO)
Where UPLOAD_TO can be an absolute path.
-- UPDATE IN REPLY TO QUESTION UPDATE --
If you don't need such security
Then you should read the documentation on FileField:
FileField.upload_to
A local filesystem path that will be appended to your MEDIA_ROOT setting to determine the value of the url attribute.
In your case, upload_to='covers' is sufficient.
Note that relative paths should be stored in the database.

Categories

Resources