Django Forms.py的表单未知字段错误

。我已经使用了我的vscode上的调试工具来调试forms.py和views.py。它返回这个。

Exception has occurred: ImproperlyConfigured
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

这是我运行manage.py runserver时遇到的错误     线程django-main-thread中的异常:     追溯(最近一次通话):

   File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 926, in _bootstrap_inner
        self.run()
      File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 870, in run
        self._target(*self._args, **self._kwargs)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
        fn(*args, **kwargs)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\management\commands\runserver.py", line 117, in
    inner_run
        self.check(display_num_errors=True)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\management\base.py", line 395, in check
        include_deployment_checks=include_deployment_checks,
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
        return checks.run_checks(**kwargs)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
        new_errors = check(app_configs=app_configs)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
        return check_resolver(resolver)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
        return check_method()
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\urls\resolvers.py", line 407, in check
        for pattern in self.url_patterns:
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\utils\functional.py", line 48, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
        patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\utils\functional.py", line 48, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
        return import_module(self.urlconf_name)
      File "c:\users\user\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
      File "<frozen importlib._bootstrap>", line 983, in _find_and_load
      File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 728, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "C:\Users\USER\Desktop\bio\apitests\crypt\crypt\urls.py", line 21, in <module>
        path('', include('cryptdjango.urls'))
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\urls\conf.py", line 34, in include
        urlconf_module = import_module(urlconf_module)
      File "c:\users\user\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
      File "<frozen importlib._bootstrap>", line 983, in _find_and_load
      File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 728, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cryptdjango\urls.py", line 2, in <module>
        from .import views
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cryptdjango\views.py", line 4, in <module>
        from .forms import CreateUserForm
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cryptdjango\forms.py", line 8, in <module>
        class CreateUserForm(UserCreationForm):
      File "C:\Users\USER\Desktop\bio\apitests\crypt\cert\lib\site-packages\django\forms\models.py", line 267, in __new__
        raise FieldError(message)
    django.core.exceptions.FieldError: Unknown field(s) (lastname, products, title, firstname, phonenumber, country, birth) specified for User

这是我的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/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# 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',
    'cryptdjango',
]

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 = 'crypt.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 = 'crypt.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/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/3.0/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/images/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

这是我的forms.py,我想知道是否应该将表单添加到我的settings.py中,我真的很困惑。在我开始创建表格之前,它工作得很好

from django.forms import ModelForm
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms


class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['country','title','firstname','lastname','birth','email','phonenumber','username','password','products']

这是我的views.py

from django.shortcuts import render, redirect
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
from .models import *
from django.contrib import messages
# Create your views here.


def hp(request):
    return render(request, 'cryptyy/hp.html')

def login(request):
    context = {}
    return render(request, 'cryptyy/login.html', context)

def signup(request):
    form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            user = form.cleaned_data.get('username')
            messages.success(request, 'Account created for ' + user)
            return redirect('login')

    context =  {'form':form}

    return render(request, 'cryptyy/sign-up.html', context)


def dashboard(request):
    return render(request, 'cryptyy/dashboard.html')
评论