Django south cannot see any field in submodule - python

I have such folder system:
project_name:
plugins
link
templates
cms_plugin.py
models.py
view.py
....
gallery
...
I want to use migration for link module, but when I do:
./manage schemamigration --initial plugins.link
south creates an empty file initial.py (models.py is not empty, and syncdb works well with it).
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['link']
If I change something in models.py - south says:
./manage.py schemamigration --auto plugins.link
Nothing seems to have changed.
I try to add app_label = 'cmsplugin', and run south with app_label:
./manage.py schemamigration --initial cmsplugin.link
but it give me the same result,
What am I doing wrong? How to create migrations for submodules?

Related

Apply a migration to Django Flatpage model

I would like to use the modeltranslation package in a Django application that uses the flatpages app.
I installed both, followed the model translation docs, and created a translation.py file, which I put in the main app (where all the global stuff lies), as I can't put it directly in the flat pages app (Django code is a requirement and is not committed to VCS).
# django/main/translation.py
from modeltranslation.translator import translator, TranslationOptions
from django.contrib.flatpages.models import FlatPage
class FlatPageTranslationOptions(TranslationOptions):
fields = ('title', 'content')
translator.register(FlatPage, FlatPageTranslationOptions)
Then I ran python manage.py makemigrations, and it created a migration file in the flatpages app /usr/local/lib/python3.8/site-packages/django/contrib/flatpages/migrations/0002_auto_20211118_1558.py. It would be again in the Django code, so I tried to simply move it to the main app at django/main/migrations/0002_flatpages_translations.py (there is already an unrelated 0001_initial.py migration, which has no dependencies):
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flatpages', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='flatpage',
name='content_en',
field=models.TextField(blank=True, null=True, verbose_name='content'),
),
migrations.AddField(
model_name='flatpage',
name='content_fr',
field=models.TextField(blank=True, null=True, verbose_name='content'),
),
migrations.AddField(
model_name='flatpage',
name='title_en',
field=models.CharField(max_length=200, null=True, verbose_name='title'),
),
migrations.AddField(
model_name='flatpage',
name='title_fr',
field=models.CharField(max_length=200, null=True, verbose_name='title'),
),
]
And... when I finally try to run the migration (python manage.py migrate), I got this error:
CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_flatpages_translations in main).
To fix them run 'python manage.py makemigrations --merge'
I tried the --merge flag, but got another error: ValueError: Could not find common ancestor of ['0001_initial', '0002_flatpages_translations']
Is it possible to achieve what I want to do?
Found a solution, so I post it here if someone has the same problem. According Django documentation, you can specify the package where migration modules can be found on a per-app basis.
So, in settings.py, add:
MIGRATION_MODULES = {
'flatpages': 'main.migrations.flatpages',
}
Then move the migration file 0002_flatpages_translations.py in django/main/migrations/flatpages/. In the case of the flatpages app, you will also need to copy the 0001_initial.py migration file from the flatpage app, inside this directory.
And you're good, Django now searches the migrations for the flatpages app in your new directory.

OperationalError: table "django_session" already exists

I have applied all solutions I could find, but still I got an operational error and also when I run project it gives error like:
You have 1 unapplied migration(s).....
I had applied all migrations.
I tried this solution:
Delete all files under migrations directory except init.py (successfully)
run $python manage.py makemigrations <appname> (successfully)
run $python manage.py sqlmigrate <appname> 001 (Successfully)
run $python manage.py migrate (Failed: operational error)
Because of 4th failure I got a statement of migrations while I ran project
What should I do?
Below is my code:
urls.py
urlpatterns = [ url(r'^$', views.index,name='index'), url(r'.*signup/$' , views.signup.as_view(), name='signup'), ]
models.py
class PatientSignup(models.Model):
Pname = models.CharField()
forms.py:
class PatientSignupForm(forms.ModelForm):
forms.CharField() # add other fileds
views.py:
class signup(TemplateView):
temp = 'personal/signup.html'
def get(self, request):
psform = PatientSignupForm()
data = PatientSignup.objects.all()
args = {'psform': psform, 'data': data}
return render(request, self.temp, args)
def post(self, request):
psform = PatientSignupForm(request.POST)
if psform.is_valid():
psform.save()
cd = psform.cleaned_data
args = {'psform': psform, 'data': data}
return render(request, self.temp, args)
Template code:
<form method="post">
{ % csrf_token %}
<div>
{{psform.as_p}}
<button type="submit"/>
</div>
</form>
Step 0) Delete the database and create it again or delete all entries in the table django_migrations and try again the migrations.
You are trying to apply migrations on already created database field. You could have run migrate --fake command, but in your case, it seems that you have multiple migrations to migrate. First of all, delete your current db by creating a backup of it. Now type,
python manage.py makemigrations app_name
At this point, you have created migration files, enter following command,
python manage.py migrate
This should have solved your migrations issue. Thanks

Django django.contrib.sites where to put migration?

the django doc says to change the sites name and domain in the django.contrib.sites framework one should use a migration [1].
But they forgot to mention where I should put this migration. I tried to create a directory named "sites" and a directory named "django.contrib.sites". But no matter in which directory I put my migration, manage.py migration always says there is nothing to update.
I also tried to run python manage.py makemigrations --empty sites, but then the migration is created in the lib directory: ve/lib/python3.5/site-packages/django/contrib/sites/migrations/0003_auto_20160904_2144.py. This may be correct behaviour, but then I cannot set my change under source control.
In case something is wrong with my migration, here it is:
from __future__ import unicode_literals
from django.db import migrations, models
def set_site_name(apps, schema_editor):
Sites = apps.get_model('django.contrib.sites', 'site')
site = Sites.objects.filter(id=1).first()
if site != None:
site.name = "name"
site.domain = "name.com"
class Migration(migrations.Migration):
initial = True
operations = [
migrations.RunPython(set_site_name),
]
So my question is: where does django expect to find those migrations?
Thank you very much in advance for your help.
[1] https://docs.djangoproject.com/en/1.10/ref/contrib/sites/#enabling-the-sites-framework
Each app in a Django project must have a unique label. Naming your app sites isn't a good idea - it will clash with the django.contrib.sites app unless you change the label in the app config class.
If you have an existing app specific to your project, you could use that app to store the data migration.
Alternatively choose a different name like mysites. Create the app with ./manage.py startapp mysite, add the app to your INSTALLED_APPS, then create a blank migration.

How to remove an app from a django projects (and all its tables)

I want to remove an app from a django project.
I want to remove
the tables of the app
the content-types
foreign-key usages of these content-types
Running manage.py migrate app_to_remove zero does not work:
django.db.migrations.migration.IrreversibleError:
Operation <RunPython <function forwards_func at 0x7ff76075d668>> in
fooapp.0007_add_bar is not reversible
I guess there are several migrations which are not reversible ...
First: Remove references in the code
remove app_to_remove from settings.INSTALLED_APPS
remove other references in urls.py or other places
Second: Clean the database
Create an empty migration for your django-project:
manage.py makemigrations your_django_project --empty
Edit the file. Here is a template:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('your_django_project', '0001_initial'),
]
operations = [
migrations.RunSQL('''
drop table if exists app_to_remove_table1;
drop table if exists app_to_remove_table2;
....
delete from auth_permission where content_type_id in (select id from django_content_type where app_label = '{app_label}');
delete from django_admin_log where content_type_id in (select id from django_content_type where app_label = '{app_label}');
delete from django_content_type where app_label = '{app_label}';
delete from django_migrations where app='{app_label}';
'''.format(app_label='app_to_remove'))
]
Run the migration, run tests.
About "drop if exists": You have two cases:
The production system: You want to drop the tables.
New development systems: These systems never had this app, and they don't have this table :-)
Note: this guide is successful with Django 3.1.1 and Python 3.8.2
Can you try this solution to clean your database and migrations first
Step 1: Delete your table from the file your_app/models.py but leave the file itself
Step 2: Check your register in the file admin.py if you have
Step 3: create migration:
manage.py makemigrations your_app
Step 4: migrate into database:
manage.py migrate
you can see the result in my example
Step 5: delete all the files in the folder your_app/migrations
Step 6: Remove migrations in the table django_migrations
python manage.py migrate --fake your_app zero
Check migrations:
python manage.py showmigrations
Step 7: Then you can remove the app completely,check reference,INSTALLED_APPS

Django Reusable Apps and migrations

I am trying to create a 'Reusable App'. I've written some database models, and then copy/pasted the folder (which is supposed to be my reusable app) into the Project I want to be using it in. I then added the folder's name to INSTALLED_APPS in my settings.
Then I used South to run:
python manage.py schemamigration test --initial --settings=settings_local
and:
python manage.py migrate test --settings=settings_local
When I tried accessing this app's models in the admin I got a relation does not exist. I went in my PostgreSQL and realized the tables were not created with those South commands.
Any idea what I am doing wrong?
UPDATE:
I am using Django 1.5.10 and South 0.7.5
The migration that is created when running schemma migration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Category'
db.create_table(u'test_category', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=200)),
))
db.send_create_signal(u'test', ['Category'])
def backwards(self, orm):
# Deleting model 'Category'
db.delete_table(u'test_category')
models = {
u'test.category': {
'Meta': {'object_name': 'Category'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'})
}
}
complete_apps = ['test']
I've generated the migrations and installed the app in a project of mine without a problem with a MySQL Db.
I've not really changed anything, but I did fix an import error in your form.
Your form inherits BaseInlineFormSet which you tried to import from django.forms but it should be imported from;
from django.forms.models import BaseInlineFormSet
I've zipped up the app as it is running in my project;
https://www.dropbox.com/s/tqyi9su942rsp1u/ubiwhere_games.zip?dl=0

Categories