django format of url import - python

I am importing some views to the urls.py file, here is what I have
from views.home import HomeView
from views.list_player import PlayerList
from views.list_game import GameList
from views.create_player import PlayerCreate
from views.create_game import GameCreate
from views.detail_player import PlayerDetail
from views.detail_game import GameDetail
from views.update_player import PlayerUpdate
from views.update_game import GameUpdate
from views.delete_player import PlayerDelete
from views.delete_game import GameDelete
However, is there a way to import them like this?
from .views import(
Home,
GameList,
PlayerList,
PlayerDetail,
GameDetail,
PlayerCreate,
GameCreate,
PlayerUpdate,
PlayerDelete,
GameUpdate,
GameDelete
)
which looks much more cleaner.

The statements are functionally equivalent.
From http://legacy.python.org/dev/peps/pep-0328/, the use of parentheses was approved for enclosing long lists of imports in a pythonic way, for Tkinter:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
LEFT, DISABLED, NORMAL, RIDGE, END)
It seems that parentheses were added for the second statement because the import list was too long.
However, you see you have varied package imports from different folders of the package. So I guess due to the intermediate folders like home, list_player, list_game you won't be able to do direct imports. So the best way I can see is doing this:
from .views import (
home,
list_player,
list_game,
create_player,
create_game,
...
)
:D

it easier to import like this:
from <appname> import views #in urls.py
and inside url patterns you can use:
path(<regex>, views.<viewname>) #url patterns

Related

How to import a model to a file in Django

I have the following structure of the project:
I have folder modules. And I have file save_to.py
I need to import a model from bedienungsanleitung app. But when I try to do it, it gives an error
No module named 'manuals_project.bedienungsanleitung'
I try to do it the following way:
from manuals_project.bedienungsanleitung.models import Link
from .bedienungsanleitung.models import Link
from bedienungsanleitung.models import Link
from ..models import Link
What is the mistake? Can someone help me?
You may try:
from bedienungsanleitung.models import Link
from manuals_project.bedienungsanleitung.models import Link
I don't see that you have models under bedienungsanleitung. Did you mean to say
from manuals_project.models import Link

cannot import the module in Python

I have the following folder structure.
check_site
- test_site
-- views.py
- app2
- app3
- modules
-- url.py
-- usability.py
module ulr.py contains one class inside - Url.py
class URL:
...
module usability.py contains one class that inherit URL class
from url import URL
class Usability(URL):
...
And then I have a view.py where I neen to import class Usability
from modules.url import URL
from modules.usability import Usability
And here is a problem. It gives me an error
from url import URL
ModuleNotFoundError: No module named 'url'
I've tried to change the import in usability.py to
from modules.url import URL but in this case it gives the error in the usability.py
Unable to import modules.url
I've also tried
from .url import URL and from check_site.modules.url import URL But these also don't work
If someone knows how to fix it, please help
Well, the problem lies here because by default Python searches for the file in the current directory but the file u want to import is not in the same directory as your program.
You should try sys.path
# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')
import file
This should work in most cases.

in django app when splitting view.py file I am getting issues with url.py

So my view file got huge and i decided to split it to smaller parts
following this answer
I created a views folder and under this folder created few view...py files
What ever was existing is still works after splitting but now when i try to create a new view files I am getting issues in url file
this is my _init_.py file located in my view folder
from views import *
from viewscategory import *
from viewssubcategory import *
from viewsitemgroup import *
from viewsmaterial import *
from viewsbomversion import *
from viewsbom import *
from viewsapprovedmanufacture import *
This my url file relevant part
from django.conf.urls import url, include,patterns
import item.views
from views import *
urlpatterns = patterns('item.views',
url(r'^approvedmanufacture/new/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_new, name="approvedmanufacture_new"),
url(r'^approvedmanufacture/edit/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_edit, name="approvedmanufacture_edit"),
url(r'^approvedmanufacture/delete/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_delete, name="approvedmanufacture_delete"),
url(r'^approvedmanufacture/approvedmanufacture_details/(?P<pk>\d+)$', item.views.approvedmanufacture_details, name="approvedmanufacture_details"),
)
and this is the error from terminal
File "C:\Users\I812624\dev\mrp\src\item\urls.py", line 58, in <module>
url(r'^approvedmanufacture/new/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.appro
vedmanufacture_new, name="approvedmanufacture_new"),
AttributeError: 'module' object has no attribute 'approvedmanufacture_new'
[03/May/2016 17:51:10]"GET /item/material/material_bomversion_details/3 HTTP/1.1
" 500 59
Even if I modify my line in ulr.py to include full path I am still getting same error
url(r'^approvedmanufacture/new/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.viewsapprovedmanufacture.approvedmanufacture_new, name="approvedmanufacture_new"),
or
url(r'^approvedmanufacture/new/(?P<pk>\d+)/(?P<uri>\S+)/$', item.viewsapprovedmanufacture.approvedmanufacture_new, name="approvedmanufacture_new"),
The funny thing in the same file I have 2 views:
-def material_bomversion_details
i had this one before I made the split
and new one
-def material_am_details
so when in shell I execute
from item.views import material_bomversion_details it runs ok,
but when I execute from item.views import material_am_details .
I am getting ImportError: cannot import name material_am_details
This is beyond my understanding
It looks like there is some kind of cache in Django framework that saved ok everything that was there before the split and is not adding anything new to it . After moving everything back to one view file everything works just fine.
In your views/__init__.py, you can fix this issue by importing views relatively:
from .viewscategory import *
from .viewssubcategory import *
from .viewsitemgroup import *
from .viewsmaterial import *
from .viewsbomversion import *
from .viewsbom import *
from .viewsapprovedmanufacture import *
And then in your urls:
from django.conf.urls import url
from item import views
urlpatterns = [
url(r'^approvedmanufacture/new/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_new, name="approvedmanufacture_new"),
url(r'^approvedmanufacture/edit/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_edit, name="approvedmanufacture_edit"),
url(r'^approvedmanufacture/delete/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.approvedmanufacture_delete, name="approvedmanufacture_delete"),
url(r'^approvedmanufacture/approvedmanufacture_details/(?P<pk>\d+)$', item.views.approvedmanufacture_details, name="approvedmanufacture_details"),
]

Pylint reporting Cyclic Import on file without imports

So Pylint (1.4.3) is reporting a Cyclic Import and it doesn't make much sense.
First of all, the file that's report has no import statements.
Second of all no files import the reference file. a __init__.py file loads configuration values from development_config (file in question) but no files
import said file.
So why is Pylint giving me this warning?
Pylint warning
************* Module heart_beat.development_config
R: 1, 0: Cyclic import (heart_beat -> heart_beat.views -> heart_beat.models) (cyclic-import)
R: 1, 0: Cyclic import (heart_beat -> heart_beat.views) (cyclic-import)
development_config
""" -------------------------- DATA BASE CONFINGURATION --------------------"""
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
SQLALCHEMY_ECHO = False
""" -------------------------- Flask Application Config --------------------"""
THREADS_PER_PAGE = 8
VERSION = "0.1"
__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
#from register_assets import register_all
app = Flask(__name__, static_url_path='/static')
# the environment variable LIMBO_SETTINGS is set in runserver, run_unit_tests
# or limbo.wsgi.
def load_configs():
"""Take all configs found in development_config.py."""
app.config.from_pyfile("development_config.py", silent=False)
load_configs()
# global SQLAlchemy configuration
db = SQLAlchemy(app)
#Create and register all static asset bundles.
#register_all(app)
#NOTE: DON'T LISTEN TO YOUR IDE! heart_beat.views is used and required.
import heart_beat.views # views contains all URL routes, Importing sets routes.
def setup_db():
"""Database creation in a file rather then a statement for easier tests."""
db.create_all()
def teardown_db():
"""Database deletion in a file rather then a statement for easier tests."""
db.drop_all()
setup_db()
views.py
from flask import request
from . import app
from . import db
from . import models
from . import exceptions as ex
models.py
import datetime
from . import exceptions
from . import db
from . import app
I believe this is currently a bug in pylint. Things that require analysis over multiple modules (for example cyclic-import and duplicate-code detection) get thrown as refactors into the last-parsed module file. For me, this ended up being an empty __init__.py file that had both of these dropped into it.
Both of these refactor messages though contain the actual module names which are problematic:
For cyclic-import, the problematic modules are listed in the parenthesis
For duplicate-code, the problematic modules are listed on the following lines starting with ==
The grouping of these is not limited to the print-out of modules, it also effects the summary report % errors / warnings by module in which that final parsed file gets the counts for the refactors and none of the modules it actually concerns get any counts from them.

Python - Library to Import Libraries

I am developing a project which has about a dozen different files. At the top of each file I have almost the identical lines which import the same libraries and initializes a connection to my DB:
import re
import urllib2
import datetime
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.sql import *
from sqlalchemy.orm.collections import *
from table_def import Team, Player, Box_Score, Game, Name_Mapper
from datetime import timedelta
from bs4 import BeautifulSoup as bs
from datetime import date, datetime, timedelta
import numpy as np
import argparse
engine = create_engine('sqlite:///ncaaf.db', echo=False)
md = MetaData(bind=engine)
Session = sessionmaker(bind=engine)
s = Session()
teams_table = Table("teams", md, autoload=True)
games_table = Table("games", md, autoload=True)
box_scores_table = Table("box_scores", md, autoload=True)
players_table = Table("players", md, autoload=True)
names_table = Table("names", md, autoload=True)
Can I make a module to import all these modules and to initialize this DB connection? Is that standard? Or dumb for some reason I am not realizing?
When you import something into your module, it becomes available as if it was declared in your module itself. So, you can do what you want like this:
In common_imports.py:
from datetime import date, datetime, timedelta
import numpy as np
import argparse
...
In main_module.py:
from common_import import *
a = np.array([]) # works fine
However this is not recommended since Explicit is better than implicit. E.g. if you do this, someone else (or even you from the future) won't understand where all these imported modules come from. Instead, try to either organize your imports better, or decompose your module into several ones. For example, in your import list I see argparse, SQL stuff and numpy, and I can't imaging single module that may need all these unrelated libraries.
If you create a package, you can import them in the __init__.py file, although I would suggest leaving them where they are to increase code-readability.

Categories