I have set the RECOMMENDS_TASK_CRONTAB = {'minute': '*/1'} in the setting , so this should repeat this every 1 minute.
And its not working,
Any one who have used this package https://djangopackages.org/packages/p/django-recommends/
could tell me what im doing wrong
This is my Models
# models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class Product(models.Model):
"""A generic Product"""
name = models.CharField(blank=True, max_length=100)
sites = models.ManyToManyField(Site)
def __str__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('product_detail', [self.id])
def sites_str(self):
return ', '.join([s.name for s in self.sites.all()])
sites_str.short_description = 'sites'
#python_2_unicode_compatible
class Vote(models.Model):
"""A Vote on a Product"""
user = models.ForeignKey(User, related_name='votes')
product = models.ForeignKey(Product)
site = models.ForeignKey(Site)
score = models.FloatField()
def __str__(self):
return "Vote"
This is my recommendations.py
# recommendations.py
from django.contrib.auth.models import User
from recommends.providers import RecommendationProvider
from recommends.providers import recommendation_registry
from .models import Product, Vote
class ProductRecommendationProvider(RecommendationProvider):
def get_users(self):
return User.objects.filter(is_active=True, votes__isnull=False).distinct()
def get_items(self):
return Product.objects.all()
def get_ratings(self, obj):
return Vote.objects.filter(product=obj)
def get_rating_score(self, rating):
return rating.score
def get_rating_site(self, rating):
return rating.site
def get_rating_user(self, rating):
return rating.user
def get_rating_item(self, rating):
return rating.product
recommendation_registry.register(Vote, [Product], ProductRecommendationProvider)
This is settings.py
"""
Django settings for smartTutor project.
Generated by 'django-admin startproject' using Django 1.10.5.
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
# 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 = 'qe+s3uemj302lc3ea-=54(6c9qxj2%ws2jq)(48=a__*bg+um_'
# 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.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'bootstrapform',
'el_pagination',
'markdown_deux',
'pagedown',
'simpleblog',
'myProfile',
'chartkick',
'quiz',
'recommends',
'recommends.storages.djangoorm',
'myrec'
]
import chartkick
STATICFILES_DIRS = (
chartkick.js(),
)
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 = 'smartTutor.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'template')],
'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',
'django.template.context_processors.request',
],
},
},
]
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
WSGI_APPLICATION = 'smartTutor.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'),
}
}
# 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)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_env' , 'static_root')
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_files') ]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_env' , 'media_root')
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
SITE_ID = 1
RECOMMENDS_TASK_CRONTAB = {'minute': '*/1'}
Just checked by documentation, and i think is missing some type of trigger (actually, it should be configured by Django Celery, and not by Django Recommends).
Easy solution
Use a crontab, instead of Django Celery. Your crontab should call the command python manage.py recommends_precompute.
If you don't know how to create a crontab, check here.
And then, add the following: * * * * * python /path/to/smartTutor/manage.py recommends_precompute (example of crontab for Django here).
Celery solution
If you need to make it work with Celery, i suggest you check Celery Tutorial and Celery with Django.
Warning (solved)
You are using Django 1.10, but it not worked for me. I downgraded to Django 1.9 for testing (for more information, i just added an issue).
Edited
Issue for Django 1.10 solved.
Related
I want to implement login app. all the users information are in table named 'admin_users'. I am using mysql server by xampp.
when i am authenticating using user = authenticate(username=username,password=password)
On printing user I am getting None.
I am beginner in django and I could not find out whats wrong.
If I am doing AdminUsers.objects.all() I can print all the table information.
models.py
class AdminUsers(models.Model):
username=models.CharField(max_length=50)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
class Meta:
db_table="admin_users"
view.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username,password=password)
print(user)
return render(request,'AdminUsers/login.html')
my index.html contains simple forms with username and password.
settings.py
"""
Django settings for python_test project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j*uh&s1$j-'
# 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',
'myapp'
]
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 = 'python_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),
os.path.join(BASE_DIR,'app_kanri/templates/app_kanri/')
],
'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 = 'python_test.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Not sure what your goal is with the AdminUsers model. The default django user model has flags like is_staff and is_superuser that you can use to seperate users and their permissions with regards to what they can access on the app.
Check out the docs on the user model here
You need to insert this in your settings: AUTH_USER_MODEL = 'AppName.AdminUsers' (replace AppName with the name of the app containing AdminUsers).
Your custom User model should inherit from AbstractUser to be compatible with the authentication system (right now it will not work):
class AdminUsers(AbstractUser):
department=models.CharField(max_length=50)
class Meta:
db_table='admin_users'
Now AdminUsers will inherit fields of AbstractUser (username, email, password, is_staff, ...), read this for details.
If you have already done migrations, you need to delete migrations of the default User model.
Note also that you should name the model 'AdminUser' and not 'AdminUsers'.
My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the auth_permissions table.
I've already run python manage.py makemigrations and python manage.py migrate. I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py.
Any other solutions I can try ?
admin.py
from django.contrib import admin
from .Models import *
# Register your models here.
admin.site.register(LeaveRequest)
admin.site.register(Worker)
admin.site.register(TimeSheet)
settings.py
"""
Django settings for WorkTime project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import rest_framework
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5'
SECRET_KEY = os.environ.get(
'SECRET_KEY', '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', '') != 'False'
ALLOWED_HOSTS = ['worktime-management.herokuapp.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api',
'rest_framework.authtoken',
'crispy_forms',
'web',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'WorkTime.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 = 'WorkTime.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = [
STATIC_DIR,
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Media root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Email config
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('MAIL_PASSWORD')
EMAIL_HOST_USER = os.environ.get('MAIL_USERNAME')
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# CSRF enable
CSRF_COOKIE_SECURE = True
# Rest Auth
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
# Boostrap4
CRISPY_TEMPLATE_PACK = 'bootstrap4'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.AllowAllUsersModelBackend', )
In your admin.py you are importing all of your models as from .Model import *. Python is a case-sensitive programming language if you have not manipulated your models.py file as Models.py.
I suppose from .models import * will do the trick
The above solution solves the problem. However, my Models is actually a folder, I've been trying to divide the models into different files which are stored in that folder. So for those who have the same idea, just simply change the folder's name into models and you're good to go :v
I recently installed Ckeditor on django 2.0, turns out some of the css and js files are not loading properly, I manage to get Ck read the files but now my admin body input was disappeared. missing-admin-body
As I am pretty new to django, I was wondering if I were doing anything wrong in the setting. (try to make a blog, url + generic view set up)
setting.py
>
INSTALLED_APPS = [
'personal',
'blog',
'contact',
'widget_tweaks',
'ckeditor',
'ckeditor_uploader',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, '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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/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.0/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.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URLS = '/media/'
# sendmail setting
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'kai.peng#uconn.edu'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_PORT = 1025
#CKeditor meida.root, and other setting
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_BASEPATH = "{% static 'ckeditor/ckeditor/' %}"
CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_JQUERY_URL = os.path.join(STATIC_URL,'js/jquery.min.js')
CKEDITOR_CONFIGS = {
'awesome_ckeditor': {
'toolbar': 'Basic',
},
}
here is my blog/url.py
>
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import re_path, path
urlpatterns = [
path('', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html")),
path('blog/<pk>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),]
And here is my blog/views.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import path, re_path
from django.shortcuts import render
urlpatterns = [
path(r'', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
emplate_name="blog/blog.html")),
path('blog/<int:id>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),
]
And this is my model.py
>
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140,null = True)
body = RichTextField(config_name='awesome_ckeditor')
date = models.DateTimeField(null = True)
name = models.CharField(max_length=128,null = True)
def __str__(self):
return self.title
this is the console view when I tried to refresh admin edit page
console view
I am using a python 3.6X and Django 2.0, on a Windows platform.
here is the website response with the 'empty body' site response
I suspect theres problem on the db integration or model registration, not sure....
admin.py
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)
# Register your models here.
In my case it was about installing required plugins, I added following line to CKEDITOR_CONFIGS but I forgot to download these plugins and put them inside static folder
'extraPlugins': ','.join(['codesnippet', 'prism', 'widget', 'lineutils', 'clipboard']),
I also specified plugin directories like this:
CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"
BTW make sure plugin folder's name inside this directory is the same with plugin's name, as you download plugins as zip and then extract it, its name can be a bit different...
This was all I have done to fix my issue.
I have deployed my Django(1.10) site on google compute engine, everything was working fine, but suddenly one of my model throwing 500 Server Error in admin.
I have googled around but couldn't find any solution.
All other models are displaying properly in django admin except only one and that's TaggedArticles model.
Idon't have changed anything in my site, what's can be wrong? as it happens suddenly to my site.
Here's my code:
settings.py:
"""
Django settings for brain project.
Generated by 'django-admin startproject' using Django 1.10.5.
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
# 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
# For a test push to trigger build from codeship.
# Second thing for CodeShip deployment push
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*******************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '35.202.165.136', 'brainresearchtagging.com', 'www.brainresearchtagging.com', ]
# INTERNAL_IPS = ['127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'users',
'article',
'import_export',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'brain.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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 = 'brain.wsgi.application'
# DATABASES = {
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USERNAME',
'PASSWORD': 'DB_PASS',
'HOST': 'localhost',
'PORT': '',
}
}
#Static Storage
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# 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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/assets/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ]
# Authentication
LOGIN_URL = 'users:login'
LOGIN_REDIRECT_URL = 'users:dashboard'
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'emails')
# Django Import-Export
IMPORT_EXPORT_USE_TRANSACTIONS = True
Here's Tagged Article's model:
choices = (
('yes', 'Yes'),
('no', 'No'),
('not sure', 'Not Sure'),
)
class TaggedArticle(models.Model):
user = models.ForeignKey(User, related_name='tagging')
email = models.EmailField(max_length=255)
category_fit = models.CharField(choices=choices, max_length=255)
article = models.ForeignKey(Article, related_name='articles')
link = models.URLField(max_length=255,)
relevant_feedback = models.TextField(blank=True)
category = models.CharField(max_length=255,)
created_at = models.DateTimeField(default=timezone.now, editable=False)
Here's admin.py:
class TaggedArticleAdmin(admin.ModelAdmin):
date_hierarchy = 'created_at'
fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email']
list_display = ['article', 'link', 'user', 'email', 'relevant_feedback']
list_filter = ['user', 'email']
model = TaggedArticle
admin.site.register(Tagged, TaggedArticleAdmin)
Update:
When i set debug=True, then it returns the following error:
ValueError at /admin/users/taggedarticle/
Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?
Request Method: GET
Request URL: http://www.brainresearchtagging.com/admin/users/taggedarticle/
Django Version: 1.10.5
Exception Type: ValueError
Exception Value:
Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?
Exception Location: /root/virEnv/lib/python3.6/site-packages/django/db/models/functions/datetime.py in convert_value, line 181
Python Executable: /root/virEnv/bin/python3.6
Python Version: 3.6.1
Python Path:
['/root/brain',
'/root/brain/brain',
'/root/virEnv/bin',
'/root/virEnv/lib/python36.zip',
'/root/virEnv/lib/python3.6',
'/root/virEnv/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/root/virEnv/lib/python3.6/site-packages',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf',
'/root/virEnv/lib/python3.6/site-packages/odf']
Server time: Sat, 18 Nov 2017 11:55:01 +0000
This can be a mysql timezone issue. This is assuming that you have the required libraries from the error.
Check if the below value has been set in your /etc/mysql/my.cnf in [mysqld] section (after that tag). FI no, enter it and then reboot
`default-time-zone = 'UTC`'
Once you do this and it still doesnt work try flushing after doing the above.
mysql> flush tables;
I have created a custom User model inheriting from the Django one in models.py:
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
# Create your models here.
class User(AbstractUser):
pass
# triggered as soon as a new user is saved in the db
#receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Following this link, I also add my app to INSTALLED_APP and change AUTH_USER_MODEL in settings.py:
"""
Django settings for WestMolkkyClubBackend project.
Generated by 'django-admin startproject' using Django 1.10.3.
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
# 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 = '******************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['192.168.0.12']
AUTH_USER_MODEL = 'WestMolkkyClubBackend.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework.authtoken',
'WestMolkkyClubBackend'
]
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 = 'WestMolkkyClubBackend.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 = 'WestMolkkyClubBackend.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'),
}
}
# 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/'
I have also updated admin.py:
# Register your models here.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
However I get the following errors when trying to migrate:
SystemCheckError: System check identified some issues:
ERRORS:
admin.LogEntry.user: (fields.E300) Field defines a relation with model 'WestMolkkyClubBackend.User', which is either not installed, or is abstract.
admin.LogEntry.user: (fields.E307) The field admin.LogEntry.user was declared with a lazy reference to 'WestMolkkyClubBackend.user', but app 'WestMolkkyClubBackend' doesn't provide model 'user'.
authtoken.Token.user: (fields.E300) Field defines a relation with model 'WestMolkkyClubBackend.User', which is either not installed, or is abstract.
authtoken.Token.user: (fields.E307) The field authtoken.Token.user was declared with a lazy reference to 'WestMolkkyClubBackend.user', but app 'WestMolkkyClubBackend' doesn't provide model 'user'.
Is there any mistake in my code?
I reset my project while using the custom User model during the first migration and it works. It was probably a project structure issue.