I am trying to get to grips with django and south, and I seem to have run into stale contenttype problem - and I am not able to find a fix for it on SO or google.
So, to start with I have a simple project on django==1.6 with the following on installed apps:
INSTALLED_APPS = (
'django.contrib.auth',
'django_browserid', # Load after auth
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'south',
)
AUTH_USER_MODEL = 'auth.User'
and I run a syncdb on this and do not create a superuser at this stage.
Now, I create a new app loginapp and create an AbstractUser as follows:
#loginapp/models.py
class MyUser(AbstractUser):
is_admin_enabled = models.BooleanField(default=True) # new field
and change the following on my settings.py:
AUTH_USER_MODEL = "loginapp.MyUser"
now, on the login app, I run (I add loginapp to my INSTALLED_APPS dict):
python manage.py schemamigration loginapp --initial && python manage.py migrate loginapp
..all is fine so far - I can see that south has created the new User model on my db.
Now, I go back and do a syncdb on my project and I get:
The following content types are stale and need to be deleted:
auth | user
Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.
.. I am guessing django realizes that the user model has changed and the default model is now obsolete. I tried using "yes" here and I see the DB tables are still there - presumably because syncdb does not delete database tables.
How do I avoid the above problem in the first place? I just need the user model as defined in my loginapp and not the default django user model on my DB - using south.
Would really appreciate any clues/direction to solve this issue.
I ran into a similar problem using Django 1.7 migrations to migrate auth.models.User to myapp.User (that inherits from AbstractUser), and didn't want to wipe my existing production admin logs table entries that have to do with User, so I insisted on getting this absolutely right.
Assuming myappp.models is:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
class Meta:
db_table = 'auth_user'
Here is what I came up with:
from django.db import models, migrations
import django.utils.timezone
import django.core.validators
MYAPP = 'myapp'
def migrate_func(old, new, apps, schema_editor):
ContentType = apps.get_model("contenttypes", "ContentType")
db_alias = schema_editor.connection.alias
ct = ContentType.objects.using(db_alias).get(app_label=old, model='user')
ct.app_label = new
ct.save()
def forwards_func(apps, schema_editor):
migrate_func('auth', MYAPP, apps, schema_editor)
def backwards_func(apps, schema_editor):
migrate_func(MYAPP, 'auth', apps, schema_editor)
class Migration(migrations.Migration):
dependencies = [
...
]
database_operations = [
migrations.RunPython(forwards_func, backwards_func)
]
state_operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
...
],
options={
'db_table': 'auth_user',
},
bases=(models.Model,),
),
]
operations = [
migrations.SeparateDatabaseAndState(
state_operations=state_operations),
migrations.SeparateDatabaseAndState(
database_operations=database_operations)
]
Related
I'm using Python 3.9 and Django 3.2. Here is my folder structure
+ cbapp
- settings.py
+ models
- __init__.py
- custom_user.py
- manage.py
Here's what my customer_user.py file looks like
$ cat models/custom_user.py
import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
pass
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Additionally, I have configured this in my settings.py file
AUTH_USER_MODEL = 'models.CustomUser'
However, when I run "python manage.py makemigrations", I get this error
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'models.CustomUser' that has not been installed
I have no idea what this means. I have this in my settings.py file
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cbapp',
]
...
AUTH_USER_MODEL = 'models.CustomUser'
According to Django doc, to substitute a custom User model
You create your custom user model ( you did it already )
In settings.py, point AUTH_USER_MODEL to it ( the model, you create above ) like this:
AUTH_USER_MODEL = 'myapp.MyUser'
You error is here : instead of AUTH_USER_MODEL = 'models.CustomUser'
write AUTH_USER_MODEL = 'cbapp.CustomUser'
NB : Don't point your models file but your app_name then the model_name.
I am trying to use Django's default Auth to handle register and log in.
setting.py:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
AUTH_USER_MODEL = 'books.User'
books.models.py:
class User(AbstractUser):
account_balance = models.DecimalField(max_digits=5, decimal_places=2, default=0)
views.py:
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/accounts/profile/")
else:
form = UserCreationForm()
return render(request, "registration/register.html", {'form': form,})
urls.py:
urlpatterns = patterns('',
(r'^accounts/login/$', login),
(r'^accounts/logout/$', logout),
(r'^accounts/profile/$', profile),
(r'^accounts/register/$', register),
)
I tried deleting the db.sqlite3 file and re-ran python manage.py syncdb but I still get this error message:
OperationalError at /accounts/register/
no such table: auth_user
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/register/
Django Version: 1.7b4
Exception Type: OperationalError
Exception Value:
no such table: auth_user
./manage.py migrate
If you've just enabled all the middlewares etc this will run each migration and add the missing tables.
Only thing you need to do is :
python manage.py migrate
and after that:
python manage.py createsuperuser
after that you can select username and password.
here is the sample output:
Username (leave blank to use 'hp'): admin
Email address: xyz#gmail.com
Password:
Password (again):
Superuser created successfully.
Update
You are probably getting this error because you are using UserCreationForm modelform, in which in META it contains User(django.contrib.auth.models > User) as model.
class Meta:
model = User
fields = ("username",)
And here you are using your own custom auth model, so tables related to User has not been created. So here you have to use your own custom modelform. where in Meta class, model should be your User(books.User) model
This will work for django version <1.7:
Initialize the tables with the command
manage.py syncdb
This allows you to nominate a "super user" as well as initializing any tables.
it is need to make migration before create superuser.
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
Username : admin
Password : 12345678
python manage.py runserver
Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
try running
python manage.py migrate
then run
python manage.py createsuperuser
For custom forms( if you have made your own forms) use this command to migrate
python manage.py migrate --run-syncdb
If using a custom auth model, in your UserCreationForm subclass, you'll have to override both the metaclass and clean_username method as it references a hardcoded User class (the latter just until django 1.8).
class Meta(UserCreationForm.Meta):
model = get_user_model()
def clean_username(self):
username = self.cleaned_data['username']
try:
self.Meta.model.objects.get(username=username)
except self.Meta.model.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
Before creating a custom user model, a first migration must be performed. Then install the application of your user model and add the AUTH_USER_MODEL.
As well:
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ("username",)
and
python manage.py migrate auth
python manage.py migrate
On Django 1.11 I had to do this after following instructions in docs https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model
# create default database:
./manage.py migrate
# create my custom model migration:
# running `./manage.py makemigrations` was not enough
./manage.py makemigrations books
# specify one-off defaults
# create table with users:
./manage.py migrate
Just do the following flow
$ django-admin createproject <your project name>
under <your project dict> type django-admin createapp <app name>
under <app name>/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Go to the root project. Then $python manage.py migrate
Then it asks for username and password
Just perform migrations before registering the user.
theres four steps for adding a custom user model to django
Create a CustomUser model
update project/settings.py AUTH_USER_MODEL
customize UserCreationForm & UserChangeForm
add the custom user model to admin.py
you missed customize forms , add the CustomUser and CustomUserAdmin to admin.site.register() , then makemigrations nd migrate .
#proj_app/forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('email','username',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'username',)
#proj_app/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm , CustomUserChangeForm
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email','username',]
admin.site.register(CustomUser, CustomUserAdmin)
here we extend the existing UserAdmin into CustomUserAdmin and tell django to use our new forms, custom user model, and list only the email and username of a user also we could add more of existing User fields to list_display
I have no idea what I did wrong but got to the point where I decided to clear the whole database. So I ran the command:
python manage.py flush
After that my database was clear then I ran the commands;
python manage.py makemigrations
python manage.py migrate
then:
python manage.py createsuperuser
That worked for me.
I have also faced the same problem "no such table: auth_user" when I was trying to deploy one of my Django website in a virtual environment.
Here is my solution which worked in my case:
In your settings.py file where you defined your database setting like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(os.getcwd(), 'db.sqlite3'),
}
}
just locate your db.sqlite3 database or any other database that you are using and write down a full path of your database , so the database setting will now look something like this ;
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/django/django_project/db.sqlite3',
}
}
I hope that your problem will resolve now.
python manage.py makemigrations then → python manage.py migrate fixes it.
Assuming Apps defined/installed in settings.py exist in the project directory.
Please check how many python instances are running in background like in windows go--->task manager and check python instances and kill or end task i.e kill all python instances. run again using "py manage.py runserver" command.
i hope it will be work fine....
If You did any changes in project/app then execute:
python manage.py migrate
python manage.py makemigrations
python manage.py createsuperuser
call these command
python manage.py makemigrations
python manage.py migrate
Using Django REST Framework (DRF), with django-rest-auth, I created a custom user model with one extra field. My aim is to use the django-rest-auth registration endpoint to register a new user in one request, and thus sending all the data to create a new user, including the data for the extra field.
I am using AbstractUser, since it seems recommended for beginners, where more advanced developers could use AbstractBaseUser. This is also why the following SO answers looks too complicated for what I want to achieve: link here.
I know this question has been asked multiple times, but the answers are not exactly what I am looking for. For a beginner like me this is complicated stuff.
So, my question is, can anyone explain how to achieve what I want?
I am using:
Django 2.1.4
django-allauth 0.38.0
django-rest-auth 0.9.3
djangorestframework 3.9.0
Here's the code that I have up until this point:
Used this tutorial to get to this code
settings.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!gxred^*penrx*qlb=#p)p(vb!&6t78z4n!poz=zj+a0_9#sw1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'users',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DRF_custom_user.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'DRF_custom_user.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'users.CustomUser'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
users.models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
preferred_locale = models.CharField(blank=True, null=True, max_length=2)
users.admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'preferred_locale']
admin.site.register(CustomUser, CustomUserAdmin)
users.forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('email', )
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
I went looking for an answer myself. Spend some time digging in the source code. I realize this solution may be missing the actual validation for the extra fields added to the custom user model, but I will look into that later.
What I have written below I wrote with a potential blog post in mind.
I am going to assume you know how to set up a DRF project and install the above packages. The django-rest-auth documentation is clear on how to install that package (https://django-rest-auth.readthedocs.io/en/latest/index.html), make sure to also follow the steps to install the part of django-rest-auth for user registration.
Create a new app ‘users’
This app will hold my custom code for implementing the custom user model. I also install it in the Django main settings file:
settings.py:
INSTALLED_APPS = [
...
'users',
]
Create my custom user model
Notice that I just added one custom field, but you can add whatever fields you want ofcourse.
users.models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
preferred_locale = models.CharField(max_length=2, blank=True, null=True)
Tell django to use the CustomUser model
settings.py:
…
AUTH_USER_MODEL = 'users.CustomUser'
Register Custom user model at Django admin
users.admin.py:
from django.contrib import admin
from .models import CustomUser
admin.site.register(CustomUser)
Make migrations and run them
This is the first time I do this for this project.
In command line:
python manage.py makemigrations users
python manage.py migrate
Registering new users with extra fields
If you start the Django development server now, you’ll see in the admin that you can see the custom user model, with the extra fields.
But when you go to ‘http://127.0.0.1:8000/rest-auth/registration/’ you don’t see the extra fields yet.
In the process of user registration two important classes are used, namely:
a serializer ‘rest_auth.registration.RegisterSerializer’
an adapter ‘allauth.account.adapter.DefaultAccountAdapter’
We’ll make a custom version of both of these, inheriting all the functionality of it’s parent class.
Creating a custom RegisterSerializer
Create a new file ‘serializers.py’ in the users app/folder.
users.serializers.py:
from rest_framework import serializers
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from rest_auth.registration.serializers import RegisterSerializer
class CustomRegisterSerializer(RegisterSerializer):
preferred_locale = serializers.CharField(
required=False,
max_length=2,
)
def get_cleaned_data(self):
data_dict = super().get_cleaned_data()
data_dict['preferred_locale'] = self.validated_data.get('preferred_locale', '')
return data_dict
Here I create a new field for each extra field on the custom user model. So in my case a added this:
preferred_locale = serializers.CharField(
required=False,
max_length=2,
)
Also, the get_cleaned_data method should return a dict which contains all the data for the fields that you want to have saved when registering a new user.
This is what the original method (of the default RegisterSerializer looks like):
def get_cleaned_data(self):
return {
'username': self.validated_data.get('username', ''),
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', '')
}
As you can see it returns a dictionary, containing all the data for the new user. You want to add a keyval entry to this dictionary for each extra field you have added to your custom user model.
In my case, needing only to add data for the field ‘preferred_locale’, this is the resulting method:
def get_cleaned_data(self):
data_dict = super().get_cleaned_data()
data_dict['preferred_locale'] = self.validated_data.get('preferred_locale', '')
return data_dict
Tell django to use this new serializer
settings.py:
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer',
}
Preventing errors
If you will try to register a new user, you might get the following error in the console where your development server is running:
ConnectionRefusedError: [Errno 111] Connection refused
Although a user is still created, you can fix this error by adding the following line to your settings.py file:
settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Another error that will occur when you delete a user is:
django.db.utils.OperationalError: no such table: allauth_socialaccount
To solve this, add this to your settings.py:
settings.py:
INSTALLED_APPS = [
...
'allauth.socialaccount',
]
After that, you should apply migrations before you can continue:
python manage.py migrate
Creating a custom AccountAdapter
After the above steps, going to ‘http://127.0.0.1:8000/rest-auth/registration/’ will show you the extra fields. But when you register a new user, and send the data for the extra fields, the extra field’s data is not saved.
The last thing we need to do to solve this is to create a custom AccountAdapter
In our users app/folder create a new file named ‘adapter.py’:
users.adapter.py:
from allauth.account.adapter import DefaultAccountAdapter
class CustomAccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=False):
user = super().save_user(request, user, form, commit)
data = form.cleaned_data
user.preferred_locale = data.get('preferred_locale')
user.save()
return user
Here, if you have followed the above steps correctly, you can access the data of the extra added fields in the form.cleaned_data dictionary. This is the dictionary that is returned by the get_cleaned_data method from our custom RegisterSerializer.
In the save_user method above, we can then use this data and save it to the appropriate fields, like so:
user.preferred_locale = data.get('preferred_locale')
Tell Django to use this new adapters
settings.py:
ACCOUNT_ADAPTER = 'users.adapter.CustomAccountAdapter'
Now you can register your user, using the django-rest-auth registration endpoint '/rest-auth/registration/', and send the data for the extra fields you added. This will all be saved in one request.
Again, I realize that custom validation for each field needs to be added. But that's another topic that I will dive into later, and update the post when I found out how that works precisely.
Let's break your question. Please note that I am explaining the basics of Django REST Framework to you.
Overriding User's Model
[x] Step 1: You override User model: You did this. Alternative? Yes. Create a model that has OneToOneForeignKey pointed to User model.
[x] Step 2: Use this CustomUserModel. To do this, you need to set AUTH_USER_MODEL in settings.py Link to official documentation You did this.
[ ] Step 3: Create a UserManager to handle user's registration and other information. You haven't done this.
Registration from API
[ ] Create a serializer that clearly mentions all the required fields that you're expecting from an end user. You can even use serializer.ModelSerializer if there are no custom fields.
[ ] Handle explicit verifications in serializer itself. Use def validate(self, attrs) if required. Here is the official document link.
[ ] Finally, create a view and use APIView as you will want to register a user using UserManager that you created above.
I can also refer to you an app that I built myself. Here's the link: DRF-USER. I customized User model to some extent and followed the same process.
Hope this helps.
I'm trying to use custom user model with Django CMS. I created new users app with this model:
users.models:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
Here project settings:
settings:
INSTALLED_APPS = [
'djangocms_admin_style',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django.contrib.messages',
'users',
'cms',
'menus',
...
]
AUTH_USER_MODEL = 'users.User'
Why I have this error?
manage.py makemigrations users
django.db.migrations.state.InvalidBasesError: Cannot resolve bases for [<ModelState: 'cms.PageUser'>]
This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
in an app with no migrations; see https://docs.djangoproject.com/en/1.8/topics/migrations/#dependencies for more
I ran into same problem and I followed your instruction but on step 9 I encounter this error:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'.
I got it to work by reordering your step (without commenting out the AUTH_USER_MODEL and without commenting out users from installed apps)
Removed migrations folder from users app
Started with a blank database
Ran manage.py makemigrations users
Ran manage.py migrate
Ran manage.py makemigrations
Ran manage.py migrate
I ran into the same issue. Based on a reply to https://github.com/divio/django-cms/issues/3436 I did the following which worked for me:
Removed migrations folder from users app
Commented out users from installed apps
Commented out the AUTH_USER_MODEL bit
Started with a blank database
Ran manage.py makemigrations
Ran manage.py migrate
Put back the things, I commented out previously.
Ran manage.py makemigrations users
Ran manage.py migrate
I know it's an old post but it might help others.
I am trying to get Django running on Google App Engine using Django non-rel. I am following the Django 1.5 tutorial However, when i run:
python manage.py sql polls
nothing is returned. Can anyone suggest why 'manage.py sql' is silently failing?
When I sync the database I get:
$ python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
The database is specified in settings.py as follows:
# Activate django-dbindexer for the default database
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']}
AUTOLOAD_SITECONF = 'indexes'
and I have remembered to include 'polls' in the settings.py
INSTALLED_APPS = (
# 'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'djangotoolbox',
'autoload',
'dbindexer',
'polls',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
and the models are present in polls/models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
NOTE: If I change settings.py to use a local sqlite3 database, 'manage.py sql polls' behaves as described in the tutorial. Therefore, as far as I can tell, this has nothing to do with:
the /polls directory structure
the /polls/models.py file
the python path
Why do you expect it do anything? GAE is, specifically, a non-relational (NoSQL) datastore. There is quite simply no SQL to produce.
You should be aware that GAE, even with django-non-rel, is quite different from standard Django, and following the Django tutorial is only likely to confuse you.