Reputation: 1
My final project for my Python course is making a Pizza website using Django.
I have the init.py, forms.py, main.py, manage.py, models.py, myapp.forms, settings.py, and a README.md, according to what Tabnine said I needed to run this.
Every time I go to launch the website, instead of being able to access it on 127.0.0.1:8000, it doesn't launch, and at the end, it keeps giving me ModuleNotFoundError: No module named myapp.forms, despite it being there, installed as correctly as I can tell with Pylint, and I am at a loss.
Contents of the README:
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')
A test file, for your thoughts:
"""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']
settings.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',
]
I can include the models.py, but I'm having no issues there, so I may hold onto that so no one can scoop the project up.
After typing "python manage.py startapp myapp" in the project terminal through PyCharm, it attempts to launch the app, but ends by saying, again, "ModuleNotFoundError: No module named myapp.forms. Picture of error log
(.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'
I want to be able to connect to the test website through a URL at 127.0.0.1:8000, as I've set it up to do.
If anyone knows why it is behaving this way, I would really, really appreciate the help.
Upvotes: 0
Views: 73
Reputation: 4096
You probably didn't create your project correctly. It is recommended to create your Django project using the command django-admin startproject <project_name> .
This should be done in a virtual environment which it appears you are using already. Also you should have Django installed in that environment which I guess you've done. Take note of the period .
after the the project_name
in the startproject
command. It is recommended to use this if you want a neater directory structure see the answer here Using period symbol after django-admin startproject <projectname>. Your project_name
directory should come with the files settings, WSGI, URLs etc. and in the root directory, you should see a manage.py file.
You can go ahead and create your app using the command python manage.py startapp <app_name>
This will create an app directory with models, views, files etc. this is where you should store your forms.py and your app level urls.py files which you have to create yourself see https://realpython.com/django-setup/
Your error: I am not sure why you have a main.py file, it looks to me like a views.py
. It doesn't appear in the directory tree you shared but you included the file and that is exactly where your error is coming from. So you might want to shed more light on that.
Also it appears you want to spin up Django's local web server but you're inadvertently running the command to create a new app. To run the local web server, use the command python manage.py runserver
. Ensure you have migrated your models using python manage.py makemigrations
and python manage.py migrate
commands. See the docs.
Do reach out in the comments if you need additional information or help.
Upvotes: 0