Django Project Can't Find Models After Django 1.7 Upgrade - django

I've faced many hurdles in upgrading my Django 1.6.2 project to Django 1.8.4. The latest problem which has me stumped is this one. When I start my Django dev server and try to access my site, I'm getting the following error:
Exception Type: ImportError at /
Exception Value: No module named account.models
Traceback:
File "/Users/me/venv/myproj_dj_18/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
119. resolver_match = resolver.resolve(request.path_info)
File "/Users/me/venv/myproj_dj_18/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
366. for pattern in self.url_patterns:
File "/Users/me/venv/myproj_dj_18/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
402. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/me/venv/myproj_dj_18/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
396. self._urlconf_module = import_module(self.urlconf_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
File "/www/myproj/conf/urls.py" in <module>
8. from apps.admin.views import all_admins
File "/www/myproj/apps/admin/views.py" in <module>
27. from apps.account.models import Account
This is a portion of my project's folder structure:
myproj
├── apps
│   ├── __init__.py
│   ├── account
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── forms.py
│   │   ├── models.py
│   │   ├── templates
│   │   ├── tests
│   │   ├── urls.py
│   │   └── views.py
│   ├── admin
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── forms.py
│   │   ├── models.py
│   │   ├── templates
│   │   ├── tests
│   │   ├── urls.py
│   │   └── views.py
├── conf
│   ├── __init__.py
│   ├── settings
│   │   ├── __init__.py
│   │   ├── base.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
Here is a portion of my url file:
# conf/urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.contrib import admin
from apps.admin.views import all_admins
urlpatterns = patterns('',
url(r'^account/', include('apps.account.urls')),
url(r'^members/', include('apps.members.urls')),
url(r'^admin/all_admins/$',
user_passes_test(lambda u: u.is_staff)(all_admins),
{'template': 'all_admins.html'},
name='all-admins'),
url(r'^admin/review/queue/$',
'apps.admin.views.review_queue',
{'template': 'review_queue.html'},
name='review-queue'),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('apps.home.urls')),
)
These are my installed apps:
# apps/conf/settings/base.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'apps.admin',
'apps.account',
'apps.home',
)
This is a portion of the model file:
# apps/account/models.py
from django.db import models
class Account(models.Model):
pass
I've subclassed the new AppConfig class per the docs:
# apps/account/apps.py
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'apps.account'
# apps/account/__init__.py
default_app_config = 'apps.account.apps.AccountConfig'
# apps/admin/apps.py
from django.apps import AppConfig
class MyAdminConfig(AppConfig):
name = 'apps.admin'
label = 'my_admin'
verbose_name = 'Administration'
# apps/admin/__init__.py
default_app_config = 'apps.admin.apps.MyAdminConfig'
I've checked to ensure that all my paths are mutually consistent:
$ python
>>> from django.apps import apps as myproj_apps
>>> account = myproj_apps.get_app_config('account')
>>> account.name # => 'apps.account'
>>> list(account.get_models()) # => [apps.account.models.Account]
I can also do this with no errors:
$ python
>>> from apps.account.models import Account
>>> Account.objects.get(pk=1)
I tried changing all paths described above from "apps.account.models" to "myproj.apps.account.models" but that didn't help. I've also read the Django 1.7 Applications doc but don't see what I'm doing wrong. Nothing has turned up in my web searches either. This looks like something simple. Can anyone see what I'm missing?
Thanks!

Related

unable to specify custom Django Model from nested app as AUTH_USER_MODEL

I am unable to specify a custom AUTH_USER_MODEL if that model is in a nested application.
Here is some project structure:
├── project
│   ├── settings.py
│   ├── my_parent_app
│   │   ├── __init__.py
│   │   ├── apps.py
│   │   └── my_child_app
│   │   ├── __init__.py
│   │   ├── apps.py
│   │   └── models.py
and here is some code:
project/my_parent_app/my_child_app/models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
is_a_nice_user = models.BooleanField(default=False)
project/settings.py:
INSTALLED_APPS = [
'my_parent_app',
'my_parent_app.my_child_app',
]
AUTH_USER_MODEL = 'my_parent_app.my_child_app.User'
When I try to do anything, I get this error:
ValueError: Invalid model reference 'my_parent_app.my_child_app.User'. String
model references must be of the form 'app_label.ModelName'.
This is a very similar to this question. But how can I solve this without resorting to making my_child_app a separate top-level app?
AUTH_USER_MODEL has to be in the format app_label.model_name
INSTALLED_APPS = [
'my_parent_app',
'my_parent_app.my_child_app',
]
AUTH_USER_MODEL = 'my_child_app.User'

How to import the template into a subdirectory of the templates folder in Flask?

Currently I have an API project, based on flask-restful, with documentation page created with OpenAPI (Swagger). I'm trying to create a login page, based on my structure jinja2 can not find the path to the template.
In the login script, I tried to pass the full path to the .html file, in the render_template() function, but did not find the file. Just like adding the parameter template_folder = path/to/file in app=Flask(__name__) and I did not succeed.
My Structure:
├── app
│   ├── __init__.py
│   ├── auth
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── login.py
│   ├── common
│   │   ├── __init__.py
│   │   ├── jwt.py
│   │   ├── request.py
│   │   └── utils.py
│   ├── models
│   │   ├── __init__.py
│   │   ├── core.py
│   │   └── db_app_2.py
│   ├── routes
│   │   ├── __init__.py
│   │   ├── resources.py
│   └── templates
│   ├── docs
│   │   ├── swagger.json
│   │   └── swagger.yaml
│   └── pages
│   ├── base.html
│   ├── login.html
│   └── signup.html
├── app.db
├── config.py
├── main.py
├── migrations
├── requeriments
└── tests
login.py
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, redirect, url_for
from app.models.core import db
auth = Blueprint('auth', __name__)
#auth.route('/login')
def login():
return render_template('login.html')
#auth.route('/signup')
def signup():
return render_template('signup.html')
__init__.py(main project)
from flask import Blueprint, Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_restful import Api
from config import config
from .models.core import db
from .routes.resources import TwoThings
def create_app(config_name):
app = Flask(__name__, template_folder="/templates/pages")
app.config.from_object(config[config_name])
'''Fixed path for routes the api'''
path_prefix = '/api/v1'
api_bp = Blueprint(path_prefix, __name__)
api = Api(api_bp)
from app.auth.login import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix=path_prefix)
api.add_resource(Reset, f'{path_prefix}/two_things')
app.register_blueprint(api_bp)
db.init_app(app)
Migrate(app, db)
return app
I need to create a login page, to be accessible by the browser and once logged in redirect to the documentation endpoint.
Try:
return render_template('pages/login.html')
In your login.py.

How to save uploaded files to models and serve them in templates?

I've been following the django 2 official tutorial but I'm a bit confused as how to work with images and uploaded files.
I have a project with a few apps. Let's call the project myProj and the app myApp. There is a model in myApp called myModel which has an image field myImage.
Here is my model:
from django.db import models
class myModel(models.Model):
myImage = models.ImageField(upload_to='myApp_images')
Here is my template:
<img src="{{ n.image }}"></img>
Here is my view
from django.shortcuts import get_object_or_404, render
from .models import myModel
def index(request):
n = myModel.objects[0]
context = {
'n': n,
}
return render(request, 'myModel/index.html', context)
And here is my settings:(parts I thought were relevant)
INSTALLED_APPS = [
'news.apps.myModelConfig',
'django.contrib.staticfiles',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/aran/myfiles/projects/futureCoin/media/'
Here is my myProject/urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('myModel/', include('myModel.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So I made an instance of the model through the django admin site.
Here is the directory tree after that(I removed the pycache):
.
├── myProject
│   ├── __init__.py
│   ├── models.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── media
│   └── myModel_images
│   └── myImage.jpeg
├── myModel
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   ├── models.py
│   ├── static
│   │   └── myModel
│   │   ├── images
│   │   │   └── bg.jpg
│   │   └── style.css
│   ├── templates
│   │   └── myModel
│   │   └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
Now the problem is that when I try to open the index page the image is not shown because the url to it is: http://127.0.0.1:8000/myModel/myModel_images/myImage.jpg
however if I manualy open the url:http://127.0.0.1:8000/media/myModel_images/myImage.jpg I see the right Image. Can anyone please help me understand where the problem is and how I can fix it? Any other feedback on my code would also be much appreciated.
What happens when I do n.image and why does it give me a url but a wrong url?
It's not a wrong url at all. That's because n.image returns the url path of the image like /path/to/image.jpg exactly the way that you have set up in your ImageField upload_to
myImage = models.ImageField(upload_to='myApp_images')
by default this will be prefixed by your url address and becomes 127.0.0.1:8000/path/to/image.jpg. As you can see it misses the /media/ as provided in settings.MEDIA_URL where your all images are localized.
So now by using {{ n.image.url}}, you actually call it from your settings configuration, your MEDIA_URL /media/ will be added as prefix and becomes /media/path/to/image.jpg prefixed by the url 127.0.0.1:8000
To fix it, in your template, access the image url with {{instance.field.url}}
try:
<img src="{{ n.image.url }}"></img>
instead of
<img src="{{ n.image }}"></img>

Flask Restful URLs giving 404 while in a blueprint

I am trying to use Flask restful as a Blueprint in a pattern that works for other blueprints. I keep getting a 404 error when i go to
/todos/1
My project setup is as follows:
Folder structure
├── app
│   ├── __init__.py
│   ├── mod_api
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   └── views.py
│   └── templates
│   ├── base.html
│   └── home.html
├── config.py
├── manage.py
└── requirements.txt
__init__.py
from flask import Flask
from flask_restful import Api
from flask_bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
api = Api()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
api.init_app(app)
from .main import main as main_blueprint
from .mod_api import mod_api as api_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(api_blueprint)
return app
mod_api/__init__.py
from flask import Blueprint
mod_api = Blueprint('mod_api', __name__)
from . import routes
api/routes.py
from flask_restful import Resource
from .. import api
class TodoItem(Resource):
def get(self, id):
return {'task': 'Say "Hello, World!"'}
api.add_resource(TodoItem, '/todos/<int:id>')
What am I doing wrong??
I had the same problem, the solution is:
api.init_app(api_blueprint)

Newbie Django urls, views, and templates - how can this incredibly simple django project possibly be failing?

When the user lands at http://127.0.0.1:8000/ I would like to display an html page that says "welcome." When the user goes http://127.0.0.1:8000/time/ I would like to display the current time. I have followed instructions to the t and dotted every i. My settings are below. Why do I continue to get a TemplateDoesNotExist error?
views.py
from django.template.loader import get_template
from django.shortcuts import render
import datetime
def current_datetime(request):
now = datetime.datetime.now()
current_datetime_template = get_template('current_datetime.html')
context_dict = {'current_date': now}
return render(request, current_datetime_template, context_dict)
def welcome(request):
welcome_template = get_template('welcome.html')
context_dict = {'username' : 'Sally Jenkins'}
return render(request, welcome_template, context_dict)
urls.py
from django.conf.urls.defaults import patterns, include, url
from simpletest.views import welcome, current_datetime
urlpatterns = patterns('',
url(r'^time/$', current_datetime),
url(r'^$', welcome),
)
settings.py
... # all defaults ommitted here - I changed nothing.
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
In my django project directory I have a directory called templates and it contains base.html, current_datetime.html, and welcome.html just as expected.
Please tell me what I have overlooked.
Thanks.
MORE INFO:
I am using virtualenv. Does the fact that I have two django projects in the /Users/quanda/dev/django-projects/ make any difference? I can't imagine it would. One is called "blossom" and is the main project I am working on. The other is called "simpletest" and I made it extremely simple so that I could isolate the issue I was having in my blossom project. I am using the same virtual environment for both projects. Running tree -L 2 from django-projects/ gives the following structure:
.
├── Procfile
├── blossom
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── fixtures
│   ├── manage.py
│   ├── onora
│   ├── settings.py
│   ├── settings.pyc
│   ├── sqlite3-database
│   ├── templates
│   ├── test_stuff.py
│   ├── urls.py
│   ├── urls.pyc
│   ├── views.py
│   └── views.pyc
├── requirements.txt
├── simpletest
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── manage.py
│   ├── settings.py
│   ├── settings.pyc
│   ├── templates
│   ├── urls.py
│   ├── urls.pyc
│   ├── views.py
│   └── views.pyc
└── virtual_environment
├── bin
├── django-registration-0.8-alpha-1.tar
├── include
└── lib
You're passing a template object instead of the template name, as shown here in the traceback:
/Users/quanda/dev/django-projects/simpletest/templates/<django.template.base.Template object at 0x102963910> (File does not exist)
...
File "/Users/quanda/dev/django-projects/simpletest/../simpletest/views.py" in current_datetime
9. return render(request, current_datetime_template, context_dict)
Don't pass the variable current_datetime_template - just pass 'current_datetime.html' as a string, like so:
def current_datetime(request):
now = datetime.datetime.now()
context_dict = {'current_date': now}
return render(request, 'current_datetime.html', context_dict)
Try something like this in settings.py:
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__) # for linux
# or
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).replace('\\', '/') # for windows
TEMPLATE_DIRS = (os.path.join(CURRENT_PATH, 'templates'),) # for template dirs
Suppose foobar is your django project. Then welcome.html should be resides in /foobar/templates/welcome.html
and In settings:
TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__),"templates"),
) #for linux and windows