我是一位新手。我刚开始写一个 Django 项目。它被称为 iRayProject,由两个应用程序 iRay_user_authentication 和 iRay_working_with_notes 组成:
此处查看项目结构
iRay_user_authentication - 这是一个标准的 Django 应用程序,用于注册。
以下是它的 urls.py:
在views.py中,我想使用重定向将注册用户发送到项目的第二个应用程序。
但是当尝试从第二个views.py文件中导入函数时,会出现问题。
以下是它的 urls.py:
from django.urls import path
from .views import login_user, registration
urlpatterns = [
path('', login_user, name='login_user'),
path('registration', registration, name='registration'),
]
在views.py中,我想使用重定向将注册用户发送到项目的第二个应用程序。
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from ..iRay_working_with_notes.views import list_notes
def login_user(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/login.html', {'form': AuthenticationForm})
def registration(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm})
else:
if '_guest' in request.POST:
pass
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect(list_notes)
except IntegrityError:
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm,
'error': 'name is busy '
})
else:
return render(request, 'todo_app/registration.html', {'form': UserCreationForm,
'error': 'passwords not math'})
但是当尝试从第二个views.py文件中导入函数时,会出现问题。
from django.shortcuts import render
def list_notes(request):
return render(request, 'iRay_working_with_notes/list_notes.html')
我遇到了一个错误:
ImportError: 尝试相对于顶级包之外的位置进行导入
我发现有很多理论信息可以解释这个错误的原因。 但我仍然无法确定是否有一种简单的方法来实现相对或绝对导入,或者是我的项目结构不正确?
PYTHONPATH
中,并成为导入基础。 - Klaus D.