I use virtualenv for django.
And run python manage.py runserver at cmd.
In this site, the questions like importError most of them didn't be
solved.
with my question, some day it can be sovled in the end. >_<
(virtual_env_django_1.7)cundi#cundideAir ~/P/Forum> python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/cundi/PycharmProjects/Forum/accounts/models.py", line 6, in <module>
from my_forum.models import Topic, Post
File "/Users/cundi/PycharmProjects/Forum/my_forum/models.py", line 9, in <module>
from utils.bbs_utils import get_delta_time
File "/Users/cundi/PycharmProjects/Forum/utils/bbs_utils.py", line 6, in <module>
from utils import conf
File "/Users/cundi/PycharmProjects/Forum/utils/conf.py", line 4, in <module>
from accounts.models import ForumProfile
ImportError: cannot import name ForumProfile
Using google searched similar Error.But has not solve it.
This is my accounts.models.py files.
may be there is a problem.
class BaseSiteUser(models.Model):
# you can get user info like this: user.base_site_user_set.all()[0]
user = models.OneToOneField(User)
class Profile(BaseSiteUser):
nickname = models.CharField(max_length=12, blank=True, null=True)
user_avatar = models.BooleanField(default=True)
avatar_img = models.ImageField(blank=True, null=True, upload_to='avatar', default='avatar/d_avatar.png')
description = models.TextField(null=True, blank=True)
address = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=11, null=True, blank=True)
born_date = models.DateField(
verbose_name=u'出生日期', null=True, blank=True, default=None)
date_created = models.DateField(null=True, blank=True, verbose_name=u'账户创建日期', auto_now_add=True)
class ForumProfile(Profile):
favorite = models.ManyToManyField(Topic, verbose_name='fav_user', related_name='fav', blank=True)
vote = models.ManyToManyField(Topic, verbose_name='vote_user', related_name='vote', blank=True)
coins = models.IntegerField(default=0, blank=True, null=True)
location = models.CharField(max_length=20, blank=True, null=True)
last_activity = models.DateTimeField(auto_now_add=True)
last_posttime = models.DateTimeField(auto_now_add=True)
signature = models.CharField(max_length=128, default='This guy is lazy that nothing to leave')
website = models.URLField(blank=True, null=True)
This is model.py file's some snippet. Hope it will help.
Does has something wrong with settings.py ?
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '1-ygln+^^7=5=c)u3#2ozm#jiu)6=65m((rg09pwl069242#vc'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'accounts',
'my_forum',
'utils',
'blog',
'django.contrib.humanize',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Forum.urls'
WSGI_APPLICATION = 'Forum.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static', 'static_files'),)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'templates/public'),
)
MAX_UPLOAD_SIZE = "524288"
EMAIL_USE_TLS = True
EMAIL_HOST = ''
EMAIL_PORT = 465
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
Related
In django admin database I am not getting expected view. I am following the tutorials to make a quiz app in Django. I did exactly as shown in video but still I am not getting same output. I have attached the picture of expected view and picture of what I am getting.
Getting This:
Expecting This:
models.py (in quiz):
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Quiz(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=70)
slug = models.SlugField(blank=True)
roll_out = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['timestamp',]
verbose_name_plural = 'Quizzes'
def __str__(self):
return self.name
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
label = models.CharField('Question', max_length=255)
order = models.IntegerField(default=0)
def __str__(self):
return self.label
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
label = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.label
class QuizTaker(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
score = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
date_finished = models.DateTimeField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
class UserAnswer(models.Model):
quiz_taker = models.ForeignKey(QuizTaker,on_delete=models.CASCADE)
quistion = models.ForeignKey(Question,on_delete=models.CASCADE)
answer = models.ForeignKey(Answer,on_delete=models.CASCADE)
def __str__(self):
return self.question.label
In admin.py
from django.contrib import admin
import nested_admin
from .models import Quiz, Question, Answer, QuizTaker, UserAnswer
# Register your models here.
class AnswerInline(nested_admin.NestedTabularInline):
model = Answer
extra = 4
max_num = 4
class QuestionInline(nested_admin.NestedTabularInline):
model = Question
inline = [AnswerInline]
extra = 5
class QuizAdmin(nested_admin.NestedModelAdmin):
inline = [QuestionInline,]
class UserAnswerInline(admin.TabularInline):
model = UserAnswer
class QuizTakerAdmin(admin.ModelAdmin):
inline = [UserAnswerInline,]
admin.site.register(Quiz,QuizAdmin)
admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(QuizTaker,QuizTakerAdmin)
admin.site.register(UserAnswer)
In settings.py
"""
Django settings for assignment2 project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u1e72cel3t20c3m5wvetnl*7w6x8srf4f#ncx6x=7*0k-w^#%x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'bootstrap4',
'accounts.apps.AccountsConfig',
'quiz',
'nested_admin',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'assignment2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'assignment2.wsgi.application'
ASGI_APPLICATION = 'assignment.routing.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
LOGIN_REDIRECT_URL = 'test'
LOGOUT_REDIRECT_URL = 'thanks'
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
I want to add video to my django template. When I add it, video is unforwardable (I can't skip this video to other point, I can just play it from start to the end). Excatly the same issue happens when I open link to video in new browser tab.
When I close/refresh this page console shows:
[19/Jun/2019 11:22:23] "GET / HTTP/1.1" 200 9386
[19/Jun/2019 11:22:23] "GET /media/audio_and_video/videoplayback_lzlCjOR_Ftjx0GJ.mp4 HTTP/1.1" 200 9431145
[19/Jun/2019 11:22:24] "GET / HTTP/1.1" 200 9386
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 44798)
Traceback (most recent call last):
File "/usr/lib/python3.7/socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.7/socketserver.py", line 720, in __init__
self.handle()
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle
self.handle_one_request()
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
----------------------------------------
Model:
class Track(models.Model):
title = models.CharField(max_length=40, null=True)
description = models.CharField(max_length=500, null=True)
author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension])
audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension])
favourite = models.BooleanField(default=False)
def __str__(self):
return self.title
Template (".fields" because I use vuejs, but link to video works exactly as src='{{ track.audio_or_video.url }}', error was happening even when I wasn't using vue):
<video width='400' controls>
<source :src="'/media/' + track.fields.audio_or_video" type='video/mp4'>
Your browser does not support the video tag.
</video>
urls.py (main file from projectname/projectname):
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('profiles/', include('profiles.urls')),
path('', include('app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings (I removed comments/database settings to short code):
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'rvl%g^%p$=vd1^_#j0yr2uy55*hr%)60wr&bk(#a&2qe==m54r'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'profiles',
'app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MusicApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MusicApp.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'WebMediaFilesEditor',
'USER': 'root',
'PASSWORD': 'DemoPass#00',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
SITE_URL = "http://127.0.0.1:8000"
I found that! I had to install another media player for my PC - I installed VLC and made it default software to openning .mp4s in my system, and then it worked in chrome as well.
I'm trying to migrate my apps, so this error it's happening "django.db.utils.ProgrammingError: relation "users_user" does not exist".
I tried with many ways and this not running. I'm using multi-tenant configuration. Help me please.
My manage.py migrate_schemas --list
[standard:public] admin
[standard:public] [ ] 0001_initial
[standard:public] [ ] 0002_logentry_remove_auto_add
[standard:public] [ ] 0003_auto_20171127_1309
[standard:public] auth
[standard:public] [X] 0001_initial
[standard:public] [X] 0002_alter_permission_name_max_length
[standard:public] [X] 0003_alter_user_email_max_length
[standard:public] [X] 0004_alter_user_username_opts
[standard:public] [X] 0005_alter_user_last_login_null
[standard:public] [X] 0006_require_contenttypes_0002
[standard:public] [X] 0007_alter_validators_add_error_messages
[standard:public] contenttypes
[standard:public] [X] 0001_initial
[standard:public] [X] 0002_remove_content_type_name
[standard:public] foundation
[standard:public] (no migrations)
[standard:public] sessions
[standard:public] [ ] 0001_initial
[standard:public] sites
[standard:public] [X] 0001_initial
[standard:public] [X] 0002_alter_domain_unique
[standard:public] tenants
[standard:public] (no migrations)
[standard:public] users
[standard:public] [X] 0001_initial
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py",
line 350, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py",
line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line
348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line
399, in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-
packages\tenant_schemas\management\commands\migrate_schemas.py", line 53,
in handle
executor.run_migrations(tenants=tenants)
File "C:\Python27\lib\site-
packages\tenant_schemas\migration_executors\base.py", line 57, in
run_migrations
if public_schema_name in tenants:
TypeError: argument of type 'TenantQueryset' is not iterable
settings.py
"""
Django settings for ViaPortal_2 project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*3*_u^(l*1ayvv+k578+^32u8ble*^d&#n=91ou%th0&1bp60^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['softvini.pythonanywhere.com',u'localhost' ]
# Application definition
SHARED_APPS = (
'tenant_schemas', # mandatory, should always be before any django app
'tenants', # you must list the app where your tenant model resides in
'django.contrib.contenttypes',
# everything below here is optional
'django.contrib.auth',
'django.contrib.sessions',
# 'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
)
TENANT_APPS = (
'django.contrib.contenttypes',
# your tenant-specific apps
'users',
'foundation',
'notifications',
)
INSTALLED_APPS = [
'tenant_schemas',
'tenants',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
#'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'widget_tweaks',
'foundation',
'users',
'notifications',
'main',
]
TENANT_MODEL = "tenants.Tenant" # app.Model
AUTH_USER_MODEL = 'users.User'
LOGIN_URL = 'auth/login/'
DATABASE_ROUTERS = (
'tenant_schemas.routers.TenantSyncRouter',
)
MIDDLEWARE_CLASSES = [
'tenant_schemas.middleware.TenantMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MIGRATION_MODULES = {
'sites': 'contrib.sites.migrations'
}
ROOT_URLCONF = 'ViaPortal_2.urls'
'''
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
'''
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_PATH, 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ViaPortal_2.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'tenant_schemas.postgresql_backend',
'NAME': 'viaportal_py',
'USER': 'postgres',
'PASSWORD': 'my_pass',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_PATH )
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage'
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, '/static/'),
# '/var/www/static/',
)
>
users.models.py
# -- coding: utf-8 --
from future import unicode_literals
from django.utils.http import urlquote
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, *args, **kwargs):
email = kwargs["email"]
email = self.normalize_email(email)
password = kwargs["password"]
kwargs.pop("password")
if not email:
raise ValueError(_('É obrigatório informar um e-mail válido'))
user = self.model(**kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def create_superuser(self, *args, **kwargs):
user = self.create_user(**kwargs)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
#property
def is_superuser(self):
return self.is_admin
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
class User(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(
verbose_name = ('Endereco de e-mail'),
unique=True,
)
first_name = models.CharField(
verbose_name = ('Nome'),
max_length=50,
blank=False,
help_text= ('Informe seu nome'),
)
last_name = models.CharField(
verbose_name= ('Sobrenome'),
max_length=50,
blank=False,
help_text= ('Informe seu sobre nome'),
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
empresa = models.ForeignKey('foundation.Empresa', blank=True, null=True)
estabelecimento = models.ForeignKey('foundation.Estabelecimento', blank=True, null=True)
def get_absolute_url(self):
return "/users/%s/" % urlquote(self.pk)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
USERNAME_FIELD = 'email'
objects = UserManager()
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile')
image_profile = models.ImageField(upload_to = 'static/users/', default = 'static/users/no-img.jpg')
Gender_Choices = (
('F', 'Feminino'),
('M', 'Masculino'),
('O', 'Outro'),
)
gender = models.CharField(max_length=1, choices= Gender_Choices)
description = models.TextField(max_length=300,blank=True, null=True)
foundation.models.py
# -- coding: utf-8 --
from future import unicode_literals
from django.db import models
from django.conf import settings
from datetime import datetime
from django.utils import timezone
# Create your models here.
# Create your models here.
class Empresa(models.Model):
cod_empresa = models.CharField(max_length=5, unique=True)
nome = models.CharField(max_length=100)
created_by = models.ForeignKey( settings.AUTH_USER_MODEL , related_name="creation_user_empresa",blank=True, null=True)
created_date = models.DateField(default=timezone.now,blank=True)
class Meta:
verbose_name = (u'Empresa')
verbose_name_plural = (u'Empresas')
def __str__(self):
return self.cod_empresa + " - " + self.nome
def __unicode__(self):
return self.cod_empresa + " - " + self.nome
class Estabelecimento(models.Model):
cod_estabelecimento = models.CharField(max_length=5, unique=True)
nome = models.CharField(max_length=100)
razao_social = models.CharField(max_length=1000, blank=True)
empresa = models.ForeignKey(Empresa)
logo_estab = models.ImageField(upload_to = 'estabelecimentos/', default = 'estabelecimentos/no-estabelec.png')
created_by = models.ForeignKey( settings.AUTH_USER_MODEL , related_name="creation_user_estabelecimento",blank=True, null=True)
created_date = models.DateField(default=timezone.now,blank=True)
class Meta:
verbose_name = (u'Estabelecimento')
verbose_name_plural = (u'Estabelecimentos')
def __str__(self):
return self.cod_estabelecimento + " - " + self.nome
def __unicode__(self):
return self.cod_estabelecimento + " - " + self.nome
class CentroCusto(models.Model):
cod_centrocusto = models.CharField(max_length=20, unique=True)
nome = models.CharField(max_length=100)
estabelecimento = models.ForeignKey(Estabelecimento)
created_by = models.ForeignKey( settings.AUTH_USER_MODEL , related_name="creation_user_centrocusto",blank=True, null=True)
created_date = models.DateField(default=timezone.now,blank=True)
class Meta:
verbose_name = (u'Centro de Custo')
verbose_name_plural = (u'Centros de Custos')
def __str__(self):
return self.cod_centrocusto + " - " + self.nome
def __unicode__(self):
return self.cod_centrocusto + " - " + self.nome
class Departamento(models.Model):
nome = models.CharField(max_length=100)
estabelecimento = models.ForeignKey(Estabelecimento)
centroCusto = models.ForeignKey(CentroCusto)
created_by = models.ForeignKey( settings.AUTH_USER_MODEL , related_name="creation_user_departamento" ,blank=True, null=True)
created_date = models.DateField(default=timezone.now,blank=True)
class Meta:
verbose_name = (u'Centro de Custo')
verbose_name_plural = (u'Centros de Custos')
def __str__(self):
return self.nome
def __unicode__(self):
return self.nome
did you manage to solve this issue ? If not, this is what worked for me:
SHARED_APPS = (
'tenant_schemas', # mandatory
'apps.user',
'apps.customer', # must list the app where tenant model resides in
'django.contrib.contenttypes',
# everything below here is optional
'rest_framework',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django_extensions',
)
TENANT_APPS = (
'apps.user',
'apps.home',
'django.contrib.contenttypes',
# tenant-specific apps
)
INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS))
Migration commands:
python manage.py makemigrations customer
python manage.py makemigrations user
python manage.py migrate_schemas --shared
Just as #mjoyshuvo said
'app.user'
should be on both TENANT_APPS and SHARED_APPS due to the fact that some apps in the shared apps try to reference it and it doesn't seems to exists.
In my django app, called authentication, I created a custom user model, mostly following the django documentation.
In a previous project of mine it used to work, but now when I say:
user = User.objects.get(username=username)
I'm constantly facing an error:
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.User'.
I've tested it with both python2 and python3, django versions 1.9 and 1.10
What might be wrong?
My code:
models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, \
BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
import uuid
import base64
class UserManager(BaseUserManager):
def create_user(self, username, email, name, password=None):
user = self.model(
username=username,
email=email,
name=name,
last_login=timezone.now()
) # last_login is defined in AbstractBaseUser
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password):
user = self.create_user(
username=username,
email=None,
name=username,
password=password
)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def generate_registration_code():
return "asd"
class User(AbstractBaseUser, PermissionsMixin):
# This model should be created in the firest migration:
# https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#substituting-a-custom-user-model
# We use username, not email as primary user id, because OAuth
# implementation via python-social-auth requires this field to
# be present.
username = models.CharField(
verbose_name=_('username'),
max_length=255,
unique=True
)
email = models.EmailField(null=True, blank=True)
# name is a human-readable name used to refer to user e.g. "Martin Taylor"
# longest full name registered in guinness book is 744 letters-long
name = models.CharField(
verbose_name=_('name'),
max_length=1023,
null=True,
blank=True
)
# We don't need password and last_login fields, because they are
# already defined in AbstractBaseUser.
# is_active is a variable in AbstractBaseUser set to True, but we
# want a separate field for it.
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_('Is this user account activated?')
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Is this user allowed to the admin page')
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
code = models.CharField(
null=True,
blank=True,
default=generate_registration_code,
max_length=255,
help_text=_('''
Code to be sent via e-mail upon registration
or password recovery.
''')
)
new_password = models.CharField(
null=True,
blank=True,
default="",
max_length=255,
help_text=_('''
If user is attempting to change password, this field stores new
password until user enters confirmation code.
''')
)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __str__(self):
return self.username
def get_short_name(self):
return self.username
def get_full_name(self):
return self.username
settings.py:
"""
Django settings for simple_resserver_jwt project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import datetime
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'co0)lyiwbgi4wz#80gp&y++bga-+iqd8hxq5boiw3d$g(#!yl*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'authentication',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'simple_resserver_jwt.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'simple_resserver_jwt.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_USER_MODEL = 'authentication.User'
AUTHENTICATION_BACKENDS = ['authentication.backends.AuthBackend', ]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
with open('private') as f:
PRIVATE_KEY = f.readlines()
with open('public') as f:
PUBLIC_KEY = f.readlines()
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'authentication.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'authentication.utils.jwt_decode_handler',
# 'JWT_RESPONSE_PAYLOAD_HANDLER':
# 'authentication.utils.jwt_decode_handler',
'JWT_SECRET_KEY': PRIVATE_KEY,
'JWT_ALGORITHM': 'RS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
UPDATE:
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 474, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 434, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 471, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework_jwt/views.py", line 56, in post
if serializer.is_valid():
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 214, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 411, in run_validation
value = self.validate(value)
File "/usr/local/lib/python3.5/dist-packages/rest_framework_jwt/serializers.py", line 50, in validate
user = authenticate(**credentials)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/__init__.py", line 74, in authenticate
user = backend.authenticate(**credentials)
File "/home/smith/Projects/simple_resserver_jwt/authentication/backends.py", line 13, in authenticate
user = User.objects.get(username=username)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 198, in __get__
cls._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.User'
I'm currently following http://www.tangowithdjango.com/book/chapters/models.html .
On section 5.8 when I execute "python manage.py populate_rango.py" I got this error:
E:\PythonCode\django1\tango_with_django>python populate_rango.py
Starting Rango population script...
Traceback (most recent call last):
File "populate_rango.py", line 61, in <module>
from rango.models import Category, Page
File "E:\PythonCode\django1\tango_with_django\rango\models.py", line 1, in <module>
from django.db import models
File "C:\python27\lib\site-packages\django\db\models\__init__.py", line 5, in <module>
from django.db.models.query import Q
File "C:\python27\lib\site-packages\django\db\models\query.py", line 17, in <m
odule>
from django.db.models.deletion import Collector
File "C:\python27\lib\site-packages\django\db\models\deletion.py", line 4, in
<module>
from django.db.models import signals, sql
File "C:\python27\lib\site-packages\django\db\models\sql\__init__.py", line 4,
in <module>
from django.db.models.sql.subqueries import *
File "C:\python27\lib\site-packages\django\db\models\sql\subqueries.py", line
12, in <module>
from django.db.models.sql.query import Query
File "C:\python27\lib\site-packages\django\db\models\sql\query.py", line 22, i
n <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "C:\python27\lib\site-packages\django\db\models\sql\aggregates.py", line
9, in <module>
ordinal_aggregate_field = IntegerField()
File "C:\python27\lib\site-packages\django\db\models\fields\__init__.py", line
116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 54, in __ge
tattr__
self._setup(name)
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 49, in _set
up
self._wrapped = Settings(settings_module)
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 132, in __i
nit__
% (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'tango_with_django_project.settings' (Is
it on sys.path? Is there an import error in the settings file?): No module named
tango_with_django_project.settings
Here is the files and directory location E:\PythonCode\django1\tango_with_django>
- manage.py
- populate_rango.py
- tango_with_django [directory]
---- settings.py
---- urls.py
- rango [directory]
---- models.py
models.py
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
populate_rango.py
import os
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
p.save()
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
c.save()
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
from rango.models import Category, Page
populate()
settings.py
"""
Django settings for tango_with_django project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print BASE_DIR
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd!bvy8spg0ij7ok6o9%07*on&$1w#pxm=3+3lazxl#6s=h$yn&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'tango_with_django.urls'
WSGI_APPLICATION = 'tango_with_django.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DATABASE_PATH,
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
Your default path for the settings module is incorrect. You have tango_with_django_project.settings where your directory is tango_with_django.settings.
Thus, change the third to last line in your populate_rango.py file:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings')