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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24682155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:00:49  来源:igfitidea点击:

django: User Registration with error: no such table: auth_user

pythondjangoauthenticationauthorization

提问by user2988464

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:

我的设置.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.clickHymaning.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:

我的意见.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

我的网址.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?

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

采纳答案by ruddra

Update

更新

You are probably getting this error because you are using UserCreationFormmodelform, in which in METAit contains User(django.contrib.auth.models > User) as model.

您可能会收到此错误,因为您使用的是UserCreationFormmodelform,其中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 Userhas 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

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

回答by holdenweb

This will work for django version <1.7:

这适用于 Django <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.

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

回答by Kukosk

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 子类中,您必须覆盖元类和 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',
        )

回答by jmoz

./manage.py migrate

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

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

回答by Rahul Kant

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.

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

回答by calosh

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

回答by Rajiv Sharma

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: [email protected]
Password:
Password (again):
Superuser created successfully.

回答by Jason Muriki

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.
假设在 settings.py 中定义/安装的应用程序存在于项目目录中。

回答by Vardhman Danole

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 go--->任务管理器中一样,检查python实例并杀死或结束任务,即杀死所有python实例。使用“py manage.py runserver”命令再次运行。我希望它能正常工作......

回答by igo

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/#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