django:用户注册错误:没有这样的表:auth_user

时间:2022-09-16 19:18:55

I try to use Django's default Auth to handle register and login. And I think the procedure is pretty standard, but mine is with sth wrong.

我尝试使用Django的默认Auth来处理注册和登录。而且我觉得这个程序很标准,但我的错误。

my setting.py:

我的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'

my books.models.py:

我的books.models.py:

class User(AbstractUser):
    account_balance = models.DecimalField(max_digits=5, decimal_places=2, default=0)

my views.py:

我的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,})

my urls.py

我的urls.py

urlpatterns = patterns('',
    (r'^accounts/login/$', login),
    (r'^accounts/logout/$', logout),
    (r'^accounts/profile/$', profile),
    (r'^accounts/register/$', register),
)

Even I tried delete the db.sqlite3 and re python manage.py syncdb, there's still this error message:

即使我尝试删除db.sqlite3和re python manage.py syncdb,仍然会出现此错误消息:

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

Can someone explain and tell me what I should do?

有人可以解释并告诉我应该怎么做吗?

11 个解决方案

#1


13  

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.

您可能会收到此错误,因为您正在使用UserCreationForm模型,其中在META中它包含User(django.contrib.auth.models> User)作为模型。

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

在这里,您使用自己的自定义身份验证模型,因此尚未创建与用户相关的表。所以在这里你必须使用自己的自定义模型。在Meta类中,模型应该是您的User(books.User)模型

#2


34  

./manage.py migrate

If you've just enabled all the middlewares etc this will run each migration and add the missing tables.

如果您刚刚启用了所有中间件等,则会运行每次迁移并添加缺少的表。

#3


10  

This seems very elementary, but have you initialized the tables with the command

这看起来很简单,但是你用命令初始化了表

manage.py syncdb

This allows you to nominate a "super user" as well as initializing any tables.

这允许您指定“超级用户”以及初始化任何表。

#4


10  

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.

#5


2  

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

如果使用自定义身份验证模型,则在UserCreationForm子类中,您必须覆盖metaclass和clean_username方法,因为它引用了硬编码的User类(后者直到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',
        )

#6


1  

python manage.py makemigrations then → python manage.py migrate fixes it.

python manage.py makemigrations然后→python manage.py migrate修复它。

Assuming Apps defined/installed in settings.py exist in the project directory.

#7


0  

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.

当我尝试在虚拟环境中部署我的一个Django网站时,我也遇到了同样的问题“没有这样的表:auth_user”。

Here is my solution which worked in my case:

这是我的解决方案,在我的情况下工作:

In your settings.py file where you defined your database setting like this:

在settings.py文件中,您在其中定义了数据库设置,如下所示:

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 ;

只需找到您正在使用的db.sqlite3数据库或任何其他数据库,并记下数据库的完整路径,因此数据库设置现在看起来像这样;

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': '/home/django/django_project/db.sqlite3',
    }
}  

I hope that your problem will resolve now.

我希望你的问题现在能解决。

#8


0  

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.

在创建自定义用户模型之前,必须执行第一次迁移。然后安装用户模型的应用程序并添加AUTH_USER_MODEL。

As well:

同样:

class UserForm(UserCreationForm):

    class Meta:
        model = User
        fields = ("username",)

and

python manage.py migrate auth
python manage.py migrate

#9


0  

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....

请检查有多少python实例在后台运行,如在windows中运行--->任务管理器并检查python实例并终止或结束任务,即杀死所有python实例。使用“py manage.py runserver”命令再次运行。我希望它能正常工作....

#10


0  

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

在Django 1.11上,我必须按照文档中的说明进行操作https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substitute-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

#11


0  

Just do the following flow

只需执行以下操作即可

$ django-admin createproject <your project name>

under <your project dict> type django-admin createapp <app name>

下输入django-admin createapp

under <app name>/admin.py

/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

转到根项目。然后$ python manage.py migrate

Then it asks for username and password

然后它要求输入用户名和密码

#1


13  

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.

您可能会收到此错误,因为您正在使用UserCreationForm模型,其中在META中它包含User(django.contrib.auth.models> User)作为模型。

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

在这里,您使用自己的自定义身份验证模型,因此尚未创建与用户相关的表。所以在这里你必须使用自己的自定义模型。在Meta类中,模型应该是您的User(books.User)模型

#2


34  

./manage.py migrate

If you've just enabled all the middlewares etc this will run each migration and add the missing tables.

如果您刚刚启用了所有中间件等,则会运行每次迁移并添加缺少的表。

#3


10  

This seems very elementary, but have you initialized the tables with the command

这看起来很简单,但是你用命令初始化了表

manage.py syncdb

This allows you to nominate a "super user" as well as initializing any tables.

这允许您指定“超级用户”以及初始化任何表。

#4


10  

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.

#5


2  

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

如果使用自定义身份验证模型,则在UserCreationForm子类中,您必须覆盖metaclass和clean_username方法,因为它引用了硬编码的User类(后者直到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',
        )

#6


1  

python manage.py makemigrations then → python manage.py migrate fixes it.

python manage.py makemigrations然后→python manage.py migrate修复它。

Assuming Apps defined/installed in settings.py exist in the project directory.

#7


0  

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.

当我尝试在虚拟环境中部署我的一个Django网站时,我也遇到了同样的问题“没有这样的表:auth_user”。

Here is my solution which worked in my case:

这是我的解决方案,在我的情况下工作:

In your settings.py file where you defined your database setting like this:

在settings.py文件中,您在其中定义了数据库设置,如下所示:

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 ;

只需找到您正在使用的db.sqlite3数据库或任何其他数据库,并记下数据库的完整路径,因此数据库设置现在看起来像这样;

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': '/home/django/django_project/db.sqlite3',
    }
}  

I hope that your problem will resolve now.

我希望你的问题现在能解决。

#8


0  

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.

在创建自定义用户模型之前,必须执行第一次迁移。然后安装用户模型的应用程序并添加AUTH_USER_MODEL。

As well:

同样:

class UserForm(UserCreationForm):

    class Meta:
        model = User
        fields = ("username",)

and

python manage.py migrate auth
python manage.py migrate

#9


0  

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....

请检查有多少python实例在后台运行,如在windows中运行--->任务管理器并检查python实例并终止或结束任务,即杀死所有python实例。使用“py manage.py runserver”命令再次运行。我希望它能正常工作....

#10


0  

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

在Django 1.11上,我必须按照文档中的说明进行操作https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substitute-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

#11


0  

Just do the following flow

只需执行以下操作即可

$ django-admin createproject <your project name>

under <your project dict> type django-admin createapp <app name>

下输入django-admin createapp

under <app name>/admin.py

/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

转到根项目。然后$ python manage.py migrate

Then it asks for username and password

然后它要求输入用户名和密码