Can't create Django superuser [duplicate] - django

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

Related

Django IntegrityError: NOT NULL constraint failed with NULLABLE field

When trying to create a superuser in Django, I'm getting the error:
django.db.utils.IntegrityError: NOT NULL constraint failed: b3ack_investoruser.watchlist
I have a custom user and, the only custom field IS NULLABLE:
class InvestorUser(AbstractUser):
id = models.AutoField(primary_key=True)
watchlist = models.JSONField(default=None, blank=True, null=True)
manage.py has:
AUTH_USER_MODEL = 'b3ack.InvestorUser'
admin.py has:
from django.contrib import admin
from .models import InvestorUser
# Register your models here.
admin.site.register(InvestorUser)
I have tried
python3 manage.py sqlflush
I have redone all my migrations.
I have deleted previous migrations.
None of that works.
Follow these steps:
1 - Delete migrations Folder
2 - Delete db.sqlite3 (delete database)
3 - run command (python manage.py makemigrations your_app_name)
4 - run command (python manage.py migrate)

django: data migrate permissions

I have a bunch of new permissions which I need to migrate. I tried doing it through data migration but complains about ContentType not being available.
Doing quick research I found out that ContentType table is populated after all the migrations applied.
I even tried using update_all_contenttypes() from from django.contrib.contenttypes.management import update_all_contenttypes
which causes migration to load data which is not consistent to the fixture.
What is the best way to migrate permission data in Django?
Here is a quick and dirty way to ensure all permissions for all apps have been created:
def add_all_permissions(apps=None, schema_editor=None):
from django.contrib.auth.management import create_permissions
if apps is None:
from django.apps import apps
for app_config in apps.get_app_configs():
app_config.models_module = True
create_permissions(app_config, verbosity=0)
app_config.models_module = None
class Migration(migrations.Migration):
dependencies = [('myapp', '0123_do_the_thing')]
operations = [
migrations.RunPython(add_all_permissions,
reverse_code=migrations.RunPython.noop)
# ...
]
NOTE: edited to include ruohola's excellent suggestion
There are 2 ways to solve this:
1) The ugly way:
Run manage.py migrate auth before your wanted migration
2) Recommended way:
from django.contrib.auth.management import create_permissions
def add_permissions(apps, schema_editor):
apps.models_module = True
create_permissions(apps, verbosity=0)
apps.models_module = None
# rest of code here....
Here are steps for adding custom permissions to the User model:
First create a migration file, for example under your authentication application,
Here i named it 0002_permission_fixtures.py:
account (your authentication application)
|_migrations
|__ 0001_initial.py
|__ 0002_permission_fixtures.py
|__ __init__.py
Then adding your permission objects, as follow:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
# Get models that we needs them
user = apps.get_model("auth", "User")
permission = apps.get_model("auth", "Permission")
content_type = apps.get_model("contenttypes", "ContentType")
# Get user content type object
uct = content_type.objects.get_for_model(user)
db_alias = schema_editor.connection.alias
# Adding your custom permissions to User model:
permission.objects.using(db_alias).bulk_create([
permission(codename='add_sample', name='Can add sample', content_type=uct),
permission(codename='change_sample', name='Can change sample', content_type=uct),
permission(codename='delete_sample', name='Can delete sample', content_type=uct),
])
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__latest__'),
]
operations = [
migrations.RunPython(
forwards_func,
),
]
To run this migration, first migrate contenttype model, and then migrate your application (here is account).
$ python manage.py migrate contenttypes
$ python manage.py migrate account

Django OperationalError: missing table; migration does not recognize missing table

I'm having trouble in Django 1.7, I am trying to save a user to a table, but I'm getting an error that the table does not exist.
Here is the code I'm executing:
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model
User = get_user_model()
from django.contrib.sessions.backends.db import SessionStore
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, email, *_, **__):
session_key = create_pre_authenticated_session(email)
self.stdout.write(session_key)
def create_pre_authenticated_session(email):
user = User.objects.create(email=email)
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session.save()
return session.session_key
However, at
user = User.objects.create(email=email)
I get an Error message :
django.db.utils.OperationalError: no such table: accounts_user
Here is the user model at accounts/models.py that I'm trying to use to build the table:
from django.db import models
from django.utils import timezone
class User(models.Model):
email = models.EmailField(primary_key=True)
last_login = models.DateTimeField(default=timezone.now)
REQUIRED_FIELDS = ()
USERNAME_FIELD = 'email'
def is_authenticated(self):
return True
I've run sqlmigrate against this migration with 'manage.py accounts 0001.initial' and I have gotten the correct create table SQL back, but running 'manage.py migrate' gives me the following :
Operations to perform:
Apply all migrations: sessions, admin, lists, contenttypes, accounts, auth
Running migrations:
No migrations to apply.
The migration is just the result of running 'makemigration' from the shell, no custom code. I do see accounts listed in the included applications, but the migration isn't being ran, so my site is in an odd spot where Django says the table is missing when I try to use it, but Django says it exists when I try to run the migration to create it. Why does Django erroneously think that the table already exists when I can look at the database and see that it doesn't?
#user856358 Your comment about the other sqlite file seems like the root cause. I encountered the same error, and it was resolved by removing that file and running another migration. In my case, the file was located as specified in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, '../database/db.sqlite3'),
}
}
By removing the .sqlite3 file there, I was able to successfully run the migration and resolve the no-such-table error...
django.db.utils.OperationalError: no such table: accounts_user
$ rm ../database/db.sqlite3
$ python3 manage.py migrate

django south - stale user model when using AbstractUser

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)
]

Add a field to Mezzanine blogpost

I am using Mezzanine for a project. I need to add a extra field to Mezzanine blogpost.
I notice using EXTRA_MODEL_FIELDS can do it, but it looks complex.
I also try copy the blog folder from the site-package to my project path, and then modify the models.py. but I doesn't work.
I am new to Django, can some one help?
Thanks
By do some research, now I got the answer:
1. copy the blog app from sites-package to my project
2. change my setting.py
INSTALLED_APPS = (
"blog", #it was "mezzanine.blog",
.....
3. modify the blog/models.py
add following line to class BlogPost
shop_url= models.CharField(max_length=250,null=True, blank=True)
4. migirate the table (installed South)
./manage.py schemamigration blog --auto
./manage.py migrate blog
You can create a django app (CustomBlog), add it to your installed apps
and remove or comment the Mezzanine blog:
INSTALLED_APPS = (
"CustomBlog", #it was "mezzanine.blog",
...
)
In the models.py and admin.py, of your CustomBlog, inherit from the class BlogPost of Mezzanine:
models.py
from django.db import models
from mezzanine.blog.models import BlogPost
from mezzanine.blog.models import BlogCategory
class CustomBlog(BlogPost):
# Add New Field
# example
new_field = models.CharField(max_length=255)
class CustomBlogCategory(BlogCategory):
pass
admin.py
from django.contrib import admin
from .models import CustomBlog,CustomBlogCategory
admin.site.register(CustomBlog)
admin.site.register(CustomBlogCategory)
Then in the terminal create and run migrations
python manage.py makemigrations
python manage.py migrate