我的 Python 课程的最后一个项目是使用 Django 制作一个 Pizza 网站。
我有 init.py、forms.py、main.py、manage.py、models.py、myapp.forms、settings.py 和 README.md,根据 Tabnine 所说我需要运行这个.
每次我去启动网站时,它都无法在 127.0.0.1:8000 上访问它,而是无法启动,最后,它一直给我 ModuleNotFoundError:没有名为 myapp.forms 的模块,尽管它在那里,并且安装得与 Pylint 一样正确,但我却不知所措。
自述文件内容:
PizzaProject/
├── myapp/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py # Your OrderForm should be here
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── PizzaProject/
├── manage.py
└── settings.py
apps.py:
"""
This module defines the configuration for the myapp Django app.
"""
from django.apps import AppConfig
class MyappConfig(AppConfig):
"""
Configuration class for the myapp Django app.
"""
name = 'myapp'
forms.py:
from django import forms
from django.db import models # Import models from django.db instead of django.models
class OrderForm(forms.ModelForm):
"""Form for creating and updating Order instances."""
class Meta:
"""Meta class for OrderForm."""
model = models.Model # Use models.Model instead of django.models.Model
fields = ['pizza', 'toppings', 'customer_name', 'customer_phone']
main.py:
from django.shortcuts import render, redirect
from myapp.forms import OrderForm
from myapp.models import Pizza, Topping
def menu_view(request):
"""View function for the menu page."""
pizzas = Pizza.objects.filter(is_available=True)
toppings = Topping.objects.filter(is_available=True)
return render(request, 'menu.html', {'pizzas': pizzas, 'toppings': toppings})
def confirm_order_view(request):
"""View function for the order confirmation page."""
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.calculate_total()
order.save()
form.save_m2m() # Save ManyToMany toppings
return redirect('order_success')
else:
form = OrderForm()
return render(request, 'confirm.html', {'form': form})
def success_view(request):
return render(request, 'order_success.html')
一个测试文件,供您参考:
"""This module contains test cases for the menu view."""
import django.test
from myapp.models import Pizza, Topping
class MenuViewTestCase(django.test.TestCase):
def setUp(self):
self.factory = django.test.RequestFactory()
Pizza.objects.create(name="Margherita", is_available=True)
Pizza.objects.create(name="Pepperoni", is_available=False)
Topping.objects.create(name="Cheese", is_available=True)
Topping.objects.create(name="Mushrooms", is_available=False)
myapp.forms:
from django import forms
from django.db import models # Import models from django.db instead of django.models
class OrderForm(forms.ModelForm):
"""Form for creating and updating Order instances."""
class Meta:
"""Meta class for OrderForm."""
model = models.Model # Use models.Model instead of django.models.Model
fields = ['pizza', 'toppings', 'customer_name', 'customer_phone']
设置.py:
INSTALLED_APPS = [
'myapp.apps.MyappConfig', # Add your app here#
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
我可以包含 models.py,但我在那里没有任何问题,所以我可能会保留它,这样就没有人可以抢占该项目了。
通过 PyCharm 在项目终端中输入“python manage.py startapp myapp”后,它会尝试启动该应用程序,但最终再次显示“ModuleNotFoundError:没有名为 myapp.forms 的模块”。 错误日志图片
(.venv) PS C:\Users\ME\PycharmProjects\PizzaProject> python manage.py startapp myapp
INFO: Will watch for changes in these directories: ['C:\\Users\\ME\\PycharmProjects\\PizzaProject']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [16444] using WatchFiles
Process SpawnProcess-1:
Traceback (most recent call last):
File "C:\Users\ME\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap
self.run()
File "C:\Users\ME\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\ME\PycharmProjects\PizzaProject\.venv\Lib\site-packages\uvicorn\_subprocess.py", line 80, in subprocess_started
target(sockets=sockets)
File "C:\Users\ME\PycharmProjects\PizzaProject\.venv\Lib\site-packages\uvicorn\server.py", line 65, in run
return asyncio.run(self.serve(sockets=sockets))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ME\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\ME\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 995, in exec_module
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "C:\Users\ME\PycharmProjects\PizzaProject\main.py", line 2, in <module>
from myapp.forms import OrderForm
ModuleNotFoundError: No module named 'myapp.forms'
我希望能够通过 127.0.0.1:8000 的 URL 连接到测试网站,正如我所设置的那样。如果有人知道为什么会出现这种情况,我将非常非常感谢您的帮助。
django-admin startproject <project_name> .
.
命令中
project_name
后面的句点
startproject
。如果您想要更整洁的目录结构,建议使用此选项,请参阅此处的答案在 django-admin startproject 后使用句点符号
project_name
目录应该包含文件设置、WSGI、URL 等,并且在根目录中,您应该看到一个 manage.py 文件。您可以继续使用命令创建您的应用程序
python manage.py startapp <app_name>
这将创建一个包含模型、视图、文件等的应用程序目录。这是您应该存储 forms.py 和您的应用程序级别 urls.py 文件的地方要创建自己,请参阅https://realpython.com/django-setup/
你的错误:我不确定为什么你有一个 main.py 文件,在我看来它像一个views.py
。它不会出现在您共享的目录树中,但您包含了该文件,而这正是错误的来源。所以你可能想进一步了解这一点。此外,您似乎想要启动 Django 的本地 Web 服务器,但您无意中运行了创建新应用程序的命令。要运行本地 Web 服务器,请使用命令
python manage.py runserver
。确保您已使用
python manage.py makemigrations
和
python manage.py migrate
命令迁移模型。请参阅文档