Reputation: 29
I was doing simple form handling.My project name is 'mysite' and i created the folder 'books' using startapp.I made one folder called 'templates' inside 'mysite' folder.Inside 'templates', i made one html file of search form and its name is 'search_file.html'. The code to made that html file is written below.
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
Then, i wrote the following code in views.py which is located inside 'books' folder.
from django.shortcuts import render
def search_form(request):
return render(request, 'search_form.html')
After that i wrote code in urls.py which is located in 'mysite' folder as below.
from mysite.books import views
urlpatterns = patterns('',
url(r'^search-form/$', views.search_form),
)
My file tree is shown below:
The main folder is 'mysite' and within this:
- books
- __init__.py
- admin.py
- models.py
- tests.py
- views.py
- mysite
- __init__.py
- settings.py
- urls.py
- wsgi.py
- templates
- search_form.html
- manage.py
But, when i run in browser then the error appeared mentioning these things.
ImportError at /search-form/
No module named books
What is the solution for this error?
Upvotes: 1
Views: 17367
Reputation: 11
After 8 Years i had the same Problem :D
The Solution from Ciprian Tarta worked for me. But i only needed to change "mysite.settings" to "settings" in the manage.py file
I used Django version 3.2.9 and Python version 3.9.9
Upvotes: 1
Reputation: 494
The best solution would be to just move your "books" package inside mysite/mysite/ and add books to your settings.INSTALLED_APPS
But if you want to keep it like that then:
Your main "mysite" folder is not a python package. This means you need to add init.py in the main folder, see bellow:
You should have:
mysite/
books/
__init__.py
admin.py
models.py
tests.py
views.py
templates/
search_form.html
__init__.py
settings.py
urls.py
wsgi.py
manage.py
Edit manage.py
and replace mysite.settings
with settings
Edit settings.py
and replace ROOT_URLCONF = 'mysite.urls'
with ROOT_URLCONF = 'urls'
and WSGI_APPLICATION = 'mysite.wsgi.application'
with WSGI_APPLICATION = 'wsgi.application'
Add <path to>/templates
to your settings.TEMPLATE_DIRS
Add books
to your INSTALLED_APPS
Edit wsgi.py
and replace mysite.settings
with settings
Now you should be able to do from books import views
Also as you can see, you can then remove mysite/mysite folder
Upvotes: 2