SyntaxError in Localhost:8000 Python Django - django

So I am following a Django tutorial and I have the following directory for a project:
demo/
demo/
apps/
ventas/
__init__.py
admin.py
models.py
tests.py
views.py
__init.py
__init__.py
settings.py
urls.py
wsgi.py
manage
And under admin.py I have:
from django.contrib import admin
from demo.apps.ventas.models import cliente.producto
# Register the ventas models
admin.site.register(cliente)
admin.site.register(producto)
And from models.py,
from django.db import models
class cliente(models.Model):
nombre = models.CharField(max_length=200)
apellido = models.CharField(max_length=200)
status = models.BooleanField(default=True)
class producto(models.Model):
nombre = models.CharField(max_length=200)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
But when I run python manage.py runserver from Django_tutorial2/demo, I received the
SyntaxErrro in admin.py, line 2 in localhost:8000. It still worked before I added the ventas folder.
What is wrong?

I think you want
from demo.apps.ventas.models import cliente, producto
This will import the class cliente and the class producto.

from demo.apps.ventas.models import cliente.producto
replace it with:
from demo.apps.ventas.models import cliente, producto

Related

from models import Category ModuleNotFoundError: No module named 'models' using Django

settings.py:
from django.apps import AppConfig
class CategoryConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api.category'
models.py:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
admin.py code:
from django.contrib import admin
from models import Category
admin.site.register(Category)
apps.py:
from django.apps import AppConfig
class CategoryConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api.category'
Error in the terminal:
File "/home/kickme/Desktop/lcodev/ecom/api/category/admin.py", line 2,
in
from models import Category ModuleNotFoundError: No module named 'models'
In the admin.py
from django.contrib import admin
from models import Category #this line is responsible for the break
admin.site.register(Category)
If your models.py ss in the same directory then use
from .models import Category
This means to import the model Category from the models.py file in the same directory

Cannot import <app>. Check that <path> is correct

I have a next structure of project
I want to create a signal in a blog application, but I get an error
Cannot import 'blog'. Check that 'project.blog.apps.BlogConfig.name'
is correct.
If I write default_app_config = 'blog.apps.BlogConfig' in __init__.py I get error:
No module named 'blog'
settings.py
INSTALLED_APPS = [
#...
# project apps
'project.blog',
#...
]
apps.py
class BlogConfig(AppConfig):
name = 'blog'
def ready(self):
import blog.signals
__init__.py
default_app_config = 'project.blog.apps.BlogConfig'

django-comments add a new url and a view for comments?

i am newer and study django.when i install django_comments , i need add to add a new url and view for django_comments, but it don't work.
comments folder structure:
__init__.py __pycache__/ forms.py migrations/ models.py templates/ urls.py views.py
__init__.py:
def get_model():
from comments.models import CommentModel
return CommentModel
def get_form():
from comments.forms import CommentForm
return CommentForm
and forms.py and models.py is fine work.but when i add urls.py, views.py and add the urls to main urls file. it don't work.
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('delete/<int:comment_id>/', views.delete_own_comment, 'delete_own_comment'),
]
views.py
from .models import CommentModel
#login_required
def delete_own_comment(request, comment_id):
comment = get_object_or_404(CommentModel, id=comment_id, site__pk=settings.SITE_ID)
if comment.user == request.user:
comment.is_removed = True
comment.save()
but when i add path('mycomments/', include('comments.urls')) to main urls.py, it run strange errors. can anyone help me???
It's not
django-admin startapp myapp
It's
python manage.py startapp myapp
Provided that you created before a project with
django-admin startproject myproject

flask-security ImportError: cannot import name 'db'

I know this is probably a circular import error but I cannot figure out a solution. The application, so far, is very vanilla. It is the flask-security tutorial with a models.py added. This is in preparation to add blueprints to the project.
from app import db
ImportError: cannot import name 'db'
config.py
run.py
---app
------__init__py
------models.py
run.py
from app import app
if __name__ == "__main__":
app.run()
init.py
from config import Config
import app.models
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
login_required
db = SQLAlchemy()
# Create app
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
app.config['DEBUG'] = True
db.init_app(app)
user_datastore = SQLAlchemyUserDatastore(db, models.Users,
models.usersRoleNames)
security = Security(app, user_datastore)
return app
# Views
#app.route('/')
#login_required
def home():
return render_template('index.html')
models.py
from app import db
from flask_security import UserMixin, RoleMixin
users_roles = db.Table('users_roles',
db.Column('user_id', db.Integer(), db.ForeignKey('users.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('users_role_names.id')))
class usersRoleNames(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
username = db.Column(db.String(255))
password = db.Column(db.String(255))
last_login_at = db.Column(db.DateTime())
current_login_at = db.Column(db.DateTime())
last_login_ip = db.Column(db.String(100))
current_login_ip = db.Column(db.String(100))
login_count = db.Column(db.Integer)
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('usersRoleNames', secondary=users_roles,
backref=db.backref('users',
lazy='dynamic'))
Try declaring your db object in models.py and import it in app/__init_.py
models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
app/__init__.py
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
app.config['DEBUG'] = True
from app.models import db, Users, usersRoleNames
db.init_app(app)
user_datastore = SQLAlchemyUserDatastore(db, Users,
usersRoleNames)
security = Security(app, user_datastore)
return app
I have found a simple solution to the circular import problem with flask-security. This solution is particularly useful when the models are declared across different files.
1. Create a folder named models:
All our models will live inside this folder.
Sample folder structure could look like this
models/
├── _db.py
├── __init__.py
├── tickets.py
└── users.py
0 directories, 4 files
2. Create a file named _db.py:
Declare the db object in this file.
The file name could be anything but starting the file name with an underscore ensures that the db object is always imported first when the import statements are sorted.
('VS Code provided an option to automatically sort the imports, so using that doesn't cause any issues.')
_db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
3. Import db object from _db.py file:
Now we can import the db object from the _db.py file created above:
users.py
from ._db import db
from flask_security import RoleMixin, UserMixin
users_roles = db.Table(
# Table definition
)
class usersRoleNames(db.Model, RoleMixin):
# Table definition
...
class Users(db.Model, UserMixin):
# Table definition
...
4. Import everything in __init__.py file (optional):
Create a init.py file and import all the models and the db object inside it.
__init__.py
from ._db import db
from .tickets import Tickets
from .users import Users, users_roles, usersRoleNames
'''
Below part is optional
but I like to do it anyways
'''
__all__ = [
'db',
'Tickets',
'Users',
'users_roles',
'usersRoleNames',
]
By importing everything inside the __init__.py file we can import from models folder directly.
So we can do
from .models import db, Tickets, Users
Instead of this
from .models._db import _db
from .models.tickets import Tickets
from .models.users import Users
Just a thought: I am not sure if it's a bad practice to start a python file name with an 'underscore'. If you have an opinion please share your thoughts.

Django : Unable to import model from another App

I was hoping to seek some assistance on this problem I'm having. I'm still learning Django (and Python) and come across this particular issue that I'm unable to locate an answer for. I've created a new App called "News" and setup the Model for the App. Using the Admin interface I have created some data. From my "Pages" App, I'm trying to import the News_Article class and getting the error No module named News.models.
I am struggling to see what's going wrong here.
Any assistance would be greatly appreciated.
DIR Structure
Bolton_GC [Folder]
- Bolton_GC [Folder]
- News [Folder]
- Migrations [Folder]
- __init__.py
- __init__.pyc
- admin.py
- admin.pyc
- models.py
- models.pyc
- tests.py
- views.py
- Pages [Folder]
- Migrations [Folder]
- __init__.py
- __init__.pyc
- admin.py
- admin.pyc
- models.py
- models.pyc
- tests.py
- views.py
- views.pyc
- static [Folder]
- templates [Folder]
- __init__.py
- __init__.pyc
- settings.py
- settings.pyc
- urls.py
- urls.pyc
- wsgi.py
- wsgi.pyc
- db.sqlite3
- manage.py
news\model.py
from django.db import models
from datetime import datetime
class News_Article(models.Model):
class Meta:
ordering = ['news_datetime_submitted']
news_title = models.CharField(max_length=75, verbose_name="News Title")
news_text = models.CharField(max_length=300, verbose_name="News Text")
news_active = models.BooleanField(default=True, verbose_name="News Active")
news_datetime_submitted = models.DateTimeField(default=datetime.now(), verbose_name="News Date")
def __str__(self):
return self.news_title
Pages\views.py
from django.shortcuts import HttpResponse, get_object_or_404, render
from models import Page, Announcement, Menu, Sub_Menu
from django.core.exceptions import ObjectDoesNotExist
from News.models import News_Article
import pdb
# Helper Functions
def get_announcement():
try:
return Announcement.objects.get(announcement_active=True)
except ObjectDoesNotExist:
return None
def clean_url(dirtyurl, badlist):
for item in badlist:
dirtyurl = dirtyurl.replace(item,'')
return dirtyurl[1:-1]
# View functions
def page(request):
rDict = {}
path = clean_url(request.path, ['"', "'"])
# pdb.set_trace()
p = get_object_or_404(Page, urlconf_text=path)
rDict['p'] = p
announcement = get_announcement()
if not announcement == None:
rDict['announcement'] = announcement
rDict['sitenav'] = path
rDict['menu'] = Menu.objects.all().order_by('menu_position')
return render(request, 'en/public/page.html', rDict)
Error
ImportError at /home/
No module named News.models
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Django Version: 1.8.2
Exception Type: ImportError
Exception Value:
No module named News.models
Exception Location: C:\Me\Websites\Bolton_GC\Bolton_GC\Pages\views.py in <module>, line 4
Python Executable: c:\python27\python.exe
Python Version: 2.7.9
Python Path:
['C:\\Me\\Websites\\Bolton_GC',
'c:\\python27\\lib\\site-packages\\setuptools-18.0.1-py2.7.egg',
'C:\\WINDOWS\\SYSTEM32\\python27.zip',
'c:\\python27\\DLLs',
'c:\\python27\\lib',
'c:\\python27\\lib\\plat-win',
'c:\\python27\\lib\\lib-tk',
'c:\\python27',
'c:\\python27\\lib\\site-packages']
Server time: Tue, 14 Jul 2015 13:21:14 +0100
Switch
from News.models import News_Article
to
from Bolton_GC.News.models import News_Article
Just to elaborate on #TheLifeOfSteve's answer, all the import statements are always relative to your manage.py file.
If the manage.py file was at the path Bolton_GC/Bolton_GC, then the correct import statement would just be:
from News.models import News_Article
But in the current directory structure, the following is the correct answer as pointed out by Steve.
from Bolton_GC.News.models import News_Article
There is an update in Importing and registering Models!!
Please try from .models import News_Article