ImportError: попытка относительного импорта без известного родительского пакета при запуске main.py - PullRequest
0 голосов
/ 29 мая 2020

Я использую Django 3.0 для своего проекта и хочу сделать простую страницу регистрации. Моя регистрационная информация не отображается на странице базы данных администратора. python manage.py runserver не вызывает ошибок, но admin.py и views.py имеют ошибки импорта. Я также использую тот же фрагмент кода. Вот несколько фрагментов моих admin.py, views.py, models.py и settings.py.

ошибка

[Running] python -u "g:\Study\Python\Django Project\checkproject\checkapp\views.py"
Traceback (most recent call last):
  File "g:\Study\Python\Django Project\checkproject\checkapp\views.py", line 3, in <module>
    from .models import registerPerson
ImportError: attempted relative import with no known parent package

admin.py

from django.contrib import admin
from .models import registerPerson

class register(admin.ModelAdmin):
    list_display = ['firstname', 'lastname', 'email', 'password']
admin.site.register(registerPerson,register)

views.py

from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import registerPerson

def register(request):
    return render(request,'registration.html')

def add_registration(request):
    firstname = request.POST["first_name"]
    lastname = request.POST["lastname"]
    email = request.POST["email"]
    password = request.POST["password"]
    info = registerPerson(firstname=firstname, lastname=lastname, email=email, password=password)
    info.save()
    return render(request,'registration.html')

models.py

from django.db import models

# Create your models here.

class registerPerson(models.Model):
    firstname=models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    email = models.CharField(max_length=30)
    password = models.CharField(max_length=32)

    def __str__(self):
        return self.firstname

settings.py

 ["""
    Django settings for checkProject project.

    Generated by 'django-admin startproject' using Django 3.0.6.

    For more information on this file, see
    https://docs.djangoproject.com/en/3.0/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.0/ref/settings/
    """

    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__)))
    TEMPLATES_DIR=os.path.join(BASE_DIR,'checkapp/templates')


    # 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 = '6rst-p=7+k*hq*21uynw_rj)=s2iqh668_hun-vg7+!@#uni9o'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = \[\]


    # Application definition

    INSTALLED_APPS = \[
        'checkapp.apps.CheckappConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    \]

    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 = 'checkProject.urls'

    TEMPLATES = \[
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': \[TEMPLATES_DIR\],
            '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 = 'checkProject.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/'

вот моя древовидная структура проекта

CHECKPROJECT
    checkapp
        _pycache
        migrations
        templates
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        views.py
    checkProject
        __pycache__
        __init__.py
        asgi.py
        settings.py
        urls.py
        wsgi.py
    db.sqlite3
    manage.py
...