ImportError: cannot import name 'views' from '__main__' in django - django

I made a simple web app but I got this:
My urls.py file:
from django.urls import path
from . import views
urlpatterns=[
path('',views.home,name='home')
(test) C:\Users\abc\projects\amar>C:/Users/abc/envs/test/Scripts/python.exe c:/Users/abc/projects/amar/f1/urls.py
Traceback (most recent call last):
File "c:/Users/abc/projects/amar/f1/urls.py", line 3, in <module>
from . import views
ImportError: cannot import name 'views' from '__main__'
(c:/Users/abc/projects/amar/f1/urls.py)
In views.py :
from django.shortcuts import render
def home(request):
return render(request,'home.html')
And in settings.py template, I also mention path:
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],

You're not supposed to run urls.py directly. That won't work at all.
Start the server by running manage.py runserver.

Related

django urls error when I import a non-itinerant object

I can't understand why it gives me an error when importing my views.
I don't understand where the mistake is. I deleted some apps from the project and views, will it be for that?
views
from django.shortcuts import render
from django.views.generic import ListView
from .views import Schede
class SchedeListView(ListView):
model = Schede
template_name = 'test.html'
context_object_name = 'schede'
devtest urls
from django.urls import path
from django.views.generic import TemplateView
from .views import views
urlpatterns = [
path('', TemplateView.as_view(template_name="dash.html"), name="home"),
path('test_schede/', views.SchedeListView.as_view(), name="test_schede"),
]
url general
from django.contrib import admin
from django.urls import path, include
#sitemap
from django.contrib.sitemaps.views import sitemap
from .sitemaps import StaticViewSitemap
#pdf
from pdf.views import testPdfView
sitemaps = {'static': StaticViewSitemap}
urlpatterns = [
path('admin/', admin.site.urls),
path('test/<id>/', testPdfView, name="test_pdf"),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps}),
path('', include('devtest.urls'))
]
error
C:\Users\dev\Downloads\laragon\www\scheda>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\dev\Downloads\laragon\bin\python\python-3.6.1\lib\site-packages
\django\urls\resolvers.py", line 600, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
Are your imports fine? If Schede is a model, it should be imported from models.py I believe. And it's better to specify your_app name in imports.
from .views import Schede
maybe it should be:
from your_app.models import Schede
Another thing, are you sure this import is fine?
from .views import views
Maybe it should be like this:
from your_app import views

ImportErrors cannot import app and bcrypt from flask_app and can't import db from models.py

stucture of the app
flask_app
__init__.py
models.py
routes.py
run.py
__init__.py
from flask import Flask
from flask_bcrypt import Bcrypt
import os
from flask_app.models import db
app = Flask(__name__)
db.init_app(app)
bcrypt = Bcrypt(app)
from flask_app import routes
models.py
from flask_sqlalchemy import SQLAlchemy
from flask_app import app, bcrypt
db = SQLAlchemy()
run.py
from flask_app import app
if __name__ == '__main__':
app.run(debug=True)
This happens first
Traceback (most recent call last):
File
"c:\users\cristovao\documents\mqs_development\flaskexperiment\env\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\run.py", line 4, in <module>
from flask_app import app # importing from __init__.py within flask_app package
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py", line 2, in <module>
from flask_app import app, bcrypt
ImportError: cannot import name 'app' from 'flask_app' (C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py)
and then in models.py after this error I write from flask__app.__init__ import app bcrypt and I got another error
Traceback (most recent call last):
File "c:\users\cristovao\documents\mqs_development\flaskexperiment\env\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\run.py", line 4, in <module>
from flask_app import app # importing from __init__.py within flask_app package
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py", line 2, in <module>
from flask_app.__init__ import app, bcrypt
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
ImportError: cannot import name 'db' from 'flask_app.models' (C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py)
when I run my app using flask run it gives me those import errors cannot import app and bcrypt from flask_app to models.py and can't import db from models.py to __init__py. I dont understand why since run.py is being separated from my package (flask__app).
When I use your code, I get an error because of a circular import.
ImportError: cannot import name 'app' from partially initialized module 'flask_app' (most likely due to a circular import) (/home/jugmac00/Tests/stackoverflow/flask_app/__init__.py)
I can get rid of that when I remove this line from models.py
from flask_app import app, bcrypt
The easiest way to get rid of circular imports is to use the app factory pattern.
https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/
This application factory pattern took me a while to understand, but it is really worthwile to try to understand and use it.
There is a mindblowing good video on that, from this year's Flask-Conference:
https://www.youtube.com/watch?v=xNo-eOfZH5Q
If this sounds to hard, then my advice would be... just put everything in one file - that is not too bad, unless the app grows really big.

No known parent package

I made an app called calc in the project mysite. I tried this code on urls page of polls app
from django.urls import path
from . import views
urlspattern = [
path(' ',views.index, name= 'index')]
Then I got an ImportError
File "c:\Users\Anmol\tomb\mysite\polls\urls.py", line 3, in
from . import views ImportError: attempted relative import
with no known parent package

Can I make a folder of forms and views and use an __init__.py file like models and test?

I would like to keep my views and forms separate, just like you can with models. Are you able to make a directory of views and forms, and if so, what goes in the init.py files for each.
Update:
I made my folders, but I keep getting errors. Here's all my code info:
myproject structure (abbreviated):
myproject/
myproject/
name/
forms/
__init__.py
name_form.py
models/
__init__.py
name_model.py
urls.py
views/
__init__.py
name_view.py
models/init.py
from .name_model import Name
models/name_model.py
from django.db import models
from django.urls import reverse
class Name(models.Model):
...
forms/__init__.py and views/__init__.py are blank files.
urls.py
from django.urls import path
from name.views import name_view
app_name = 'name'
urlpatterns = [
path('', views.name_view, name='name-view'),
]
forms/name_form.py
from django.forms import ModelForm, TextInput
from name.models import Name
class NameForm(ModelForm):
class Meta:
model = Name
views/name_view.py
from django.shortcuts import render, redirect
from name.forms import NameForm
def name_view(request):
...
I run python3 manage.py makemigrations in the terminal and get:
/myproject/name/views/name_view.py", line 4, in <module>
from name.forms import NameForm
ImportError: cannot import name 'NameForm'
Thinking you can't make a ModelForm without a model, I run python3 manage.py migrate and get the same error.
I created a project to isolate this issue. Without the folders it worked, unless I messed up my original code trying to get this to work.
Just make a folder for your views and a folder for your forms wherever you want them to be and put an empty __init__.py file into each folder. The purpose of the __init__.py file is to tell python to treat the folder as a module. Then make your views.py file and your forms.py file in their respective directories and now you can do...
from myproject.path.to.views import MyView
from myproject.path.to.forms import MyForm
...as if it were any other module. Which it is.

How do I reset template loader cache in Django 1.9?

I used to be able to import django.template.loader.template_source_loaders and call reset() on all loaders to reset all template loader cache, but this no longer works.
How do I reset template loader cache in Django 1.9?
My settings, just in case this is useful:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')],
'APP_DIRS': True
}
]
This is how I load my template:
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.template.response import TemplateResponse
from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import ensure_csrf_cookie
#never_cache
#ensure_csrf_cookie
def view(request, **kwargs):
try:
template = get_template('index.html')
except TemplateDoesNotExist:
return HttpResponse("Run `make template`")
return TemplateResponse(request, template)
I'm experiencing this issue on local dev using the built-in runserver, with DEBUG=True. The issue does not apply on production because the template will always exist.
Django does not cache the templates, but it does cache the list of app template directories used by the app directories loader. If you create a new directory e.g. polls/templates after starting the server, then Django will not pick up templates in this directory until the server has been restarted.
Really easy:
from django.template.utils import get_app_template_dirs
get_app_template_dirs.cache_clear()