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.
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'.
Just started a fresh Django Rest framework project and I'm getting stuck on importing a view (TodoView) in urls.py
This is a completely fresh project, all I did was add the model, view and now attempting to add the url.
File "C:\Users\Simon\Documents\GitHub\tradingjournal\django_backend\django_backend\urls.py", line 20, in <module>
from django_backend.todo.views import TodoView
ModuleNotFoundError: No module named 'django_backend.todo'
urls.py
from django.contrib import admin
from django.urls import path
from rest_framework import routers
from django_backend.todo.views import TodoView
router = routers.DefaultRouter()
router.register(r'todos', TodoView, 'todo')
urlpatterns = [
path('admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
# Create your views here.
from rest_framework import viewsets
from django_backend.todo.models import Todo
from django_backend.todo.serializers import TodoSerializer
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
settings.py
"""
Django settings for django_backend project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n3^zfbj#c&i-9v^8q(%iox!kuy#gy2liy-1b+)q21-g&nwezf('
# 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',
'corsheaders',
'todo',
]
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'django_backend.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 = 'django_backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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/3.0/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.0/howto/static-files/
STATIC_URL = '/static/'
I tried changing django_backend.todo.views to todo.views but as you can see in the screenshot it's not recognized:
In a Django project the directory name of the project really doesn't matter in the code so instead of
from django_backend.todo.views import TodoView
you need to be writing:
from todo.views import TodoView
Next you see pycharm complaining that this is not a valid import while in fact it actually is (can be seen by actually running the project). Why does this happen? It is because it considers your projects root directory (i.e. there is likely a directory above django_backend) as the sources root and hence is unable to resolve your imports. To solve this you just need to set it as the Sources root by following these steps:
Right click on the project directory i.e. django_backend (on the project structure on the left side)
Select the option "Mark Directory As"
Click "Sources root"
This question resulted from a suggestion to my original issue of getting Local day from a database that is storing things as UTC located HERE
I had an issue with getting some UTC as local time values from a database in my django app as I was doing it be 'hand' in my script, someone in that issue (located here) suggested I try running the script with django (reworking to use the django ORM) decent idea but then get this error which is coming from my models file here:
from __future__ import unicode_literals
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
# Create your models here.
class OnSiteLog(models.Model):
objects = models.Manager()
user = models.ForeignKey(User, on_delete=models.CASCADE)
...
So the full error I get is:
Traceback (most recent call last):
File "report_mailer_django.py", line 13, in <module>
from covidlog.models import OnSiteLog
File "/mnt/h/programming/web/covid19/covidlog/models.py", line 7, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.contenttypes.models import ContentType
File "/usr/local/lib/python3.6/dist-packages/django/contrib/contenttypes/models.py", line 133, in <module>
class ContentType(models.Model):
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 111, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
I am not sure what is causing this, the file I am trying to fun should be loading django stuff just fine:
import django
import os
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "covid19.settings")
settings.configure()
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from covidlog.models import OnSiteLog
from covidlog.models import CountTracker
def getCheckins():
...
...
Maybe I am missing something in my settings file?
My directory structure of my project is:
covid19/
covid19/
__init__.py
settings.py
etc...
covidlog/
__init__.py
apps.py
forms.py
models.py
views.py
etc...
manage.py
report_mailer_django.py <<- what I am trying to get to run....
Also my settings file:
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l*s*!daf#_q&mbdp-$wq&5wq-6964c2z4s49!e9c+-az42br8f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
# Application definition
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'covidlog.apps.CovidlogConfig',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'bootstrap4',
'covid19',
]
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 = 'covid19.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'covidlog/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 = 'covid19.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'MST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
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 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.