How do I get the Django admin buttons shortcuts to show - python

I am currently following the Django tutorial and when I get to the admin question area, there are no calendar button or today button shortcuts. I'm not sure where the problem is, so I'll list the files I've configured below
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
settings.py
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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1*%8b#+%9&^5#5x7(yl)kxsa94qxz(tuz6hq%)x^kozg5q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
models.py
import datetime
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
#python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
#python_2_unicode_compatible
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]

In fact in order to display datetime picker and calender you need what is called in django widget. Django has support to built-in date widget but it's not so advanced.
So it's better to use third-party package with jQuery like django-datetime-widget.
install pip install django-datetime-widget
add datetimewidget to your INSTALLED_APPS in settings.py.
in forms.py:
from datetimewidget.widgets import DateTimeWidget
class QuestionForm(forms.ModelForm):
model = Question
class Meta:
model = yourModel
widgets = {
'datetime': DateTimeWidget(attrs={'id':"yourdatetimeid"}, usel10n = True, bootstrap_version=3)
}
in template file
<head>
....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>
....
</head>
In case you want to have the datetime widget in your admin interface so check here, it's a little bit hacky and require little bit more work.

Related

Not showing Media images in Django however Static files work

I am out of my depth and would like to ask you about my challenge with some images that won't load on my project. Images and CSS from the static folder get loaded successfully. But my images from the media folder are what is not showing up with error
GET /images/uploads/2021/02/11/pexels-carly-jamieson-1478450.jpg HTTP/1.1" 404
I have already done python manage.py collectstatic plenty of times. For media files I use ckeditor image uploader. Files get uploaded fine, I can see them in the media folder. The thing is, this used to work before and now it just does not.
settings.py
import os
from pathlib import Path
from decouple import config
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['localhost']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#my apps
'blog',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'portfolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'portfolio/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 = 'portfolio.wsgi.application'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Heroku settings
cwd = os.getcwd()
if cwd == '/app' or cwd[:4] == '/tmp':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
STATIC_ROOT = os.path.join(BASE_DIR, 'assets/')
urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
app_name = "blog"
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls', namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
from django.db import models
from portfolio.utils import unique_slug_generator
from django.db.models.signals import pre_save
#from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class BlogPost(models.Model):
"""A blog entry"""
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=100, null=True, blank=True)
intro = models.TextField(blank='True')
text = RichTextUploadingField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-date_added']
def __str__(self):
return self.title
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=BlogPost)
class Contact(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
subject = models.CharField(max_length=255)
message = models.TextField()
def __str__(self):
return self.name
I've tried different suggestions from SO with no luck. I want to sincerely ask all of you Django masters for your expertise and show me the way to make the images I upload to display. I really appreciate your kindness and generosity!
settings.py:
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_THUMBNAIL_SIZE = (500, 500)
CKEDITOR_IMAGE_QUALITY = 40
CKEDITOR_BROWSE_SHOW_DIRS = True
CKEDITOR_JQUERY_URL = 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
set image backend as pillow

Django Login Required Middleware does not redirect

I'm super new to Django and I have created a middleware that should direct my users to the index page with login view when trying to access the pages that are supposed to work only for logged users. Even though I don't get any error in my terminal, it does not work. When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
movie_project/middleware.py
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_request(self, request):
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = ''
DEBUG = True
ALLOWED_HOSTS = []
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Application definition
INSTALLED_APPS = [
'movies_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectfield'
]
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',
'movie_project.middleware.LoginRequiredMiddleware',
]
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
MIDDLEWARE_CLASSES = (
'python.path.to.LoginRequiredMiddleware',
)
ROOT_URLCONF = 'movie_project.urls'
AUTH_USER_MODEL = 'movies_app.User'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
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',
'django.template.context_processors.media',
],
},
},
]
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
WSGI_APPLICATION = 'movie_project.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import editprofile
from . import views
app_name = 'movies_app'
urlpatterns = [
path('', views.login, name='login'),
path('browse/', views.index, name='index'),
path('register/', views.register, name='register'),
path('movies/', views.allMovies, name='allMovies'),
path('movies/<int:pk>/', views.movie, name='movie'),
path('movies/<int:pk>/rate', views.addRating, name='rate'),
path('my-list/', views.myMovies, name='my-list'),
path('my-list/<int:pk>/delete', views.deleteFavoriteMovie, name='favorite-movie-delete'),
path('profile/', views.profile, name='register'),
path('editprofile/', views.editprofile, name='editprofile'),
path('logout/', views.logout, name='logout'),
path('movie-video', views.movieVideo, name='movie-video')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Anyone knows where can be a problem? Thank you so much for any help!
Your login required middleware does not appear to be doing anything outside of the normal. Is there a reason you have not simply used the login_required decorator on some of your views?
This decorator can be added to any (class based or function based) view where authentication is required. For example
from django.contrib.auth.decorators import login_required
#login_required
def movies_list(request):
...
This will then automatically render the view for all users who are logged in and otherwise redirect the user to the LOGIN_URL if not authenticated.
Whilst you can run your own middleware for such auth, I would strongly use the battle-tested options within the Django framework.
In the case of your comment above:
When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
On your profile view function or class base method simply add #login_required with the appropriate import statement (from django.contrib.auth.decorators import login_required).
It's somewhat confusing to have two variables named the same thing in settings.py?
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
They're just above MIDDLEWARE_CLASSES. Here' a reference to the HTTPResponseRedirect. https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpResponseRedirect In other words, delete the one that says movies_app.views.index

Django: Getting 404 Error After Adding Views, Models and URLs Correctly

I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error.
It looks like this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/gamereview/
Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order:
admin/
[name='hw']
gamereview [name='gamelist']
The current path, gamereview/, didn't match any of these.
Here are my codes of models.py inside gamereview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Tag(models.Model):
label = models.CharField(max_length=20)
def __str__(self):
return self.label
class Game(models.Model):
title = models.CharField(max_length=100)
developer = models.CharField(max_length=100)
platform = models.CharField(max_length=50, default='null')
label_tag = models.ManyToManyField(Tag)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Review(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
review = models.CharField(max_length=1000)
date = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.review
def save(self):
super(Review, self).save()
self.slug = '%i-%s' % (
self.id, slugify(self.game.title)
)
super(Review, self).save()
Here are my codes of urls.py inside gamereview folder:
from . import views
from django.urls import path
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
Here are my codes of views.py inside gamereview folder:
from django.shortcuts import render
def gamelist(request):
context_dict = {'via': "Using template"}
return render(request, 'gamereview/gamelist.html', context_dict)
Here are the codes of settings.py in gamerevs folder:
"""
Django settings for gamerevs project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'su9+iji4y-5+ddebbavou+166_p2ph1n2cls3a^x_n9o6yl1nq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'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 = 'gamerevs.urls'
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/gamerevs/', TEMPLATE_PATH],
'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 = 'gamerevs.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 = 'UTC'
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_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_PATH,
]
Here are my codes of urls.py under gamerevs folder:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('', include('gamereview.urls')),
]
Here are my codes of gamelist.html located inside gamereview folder of the templates folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gamelist</title>
</head>
<body>
<h1>This is Game List Page</h1>
<strong>{{ via }}</strong><br />
<img src="{% static "images/Super_Mario_Odyssey.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
</body>
</html>
I thought that logging into Django admin and adding new games and reviews from there would fix the issue. However, after doing it, I am still getting the 404 error.
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
The URL path without trailing / (slash) will give 404 for URL ending with trailing slash.
gamereview will match only gamereview
gamereview/ will match gamereview/ and will redirect gamereview to gamereview/ matching both the types of URLs.
I recommend trailling slash in every URL path (in Django).
# You need to add your app name in your settings.py file 'INSTALLED_APPS'
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gamereview',
]
Change urls.py file's (inside gamreview folder) content by;
urlpatterns = [
path('', views.gamelist, name='gamelist'),
]
and change urls.py file's (inside project directory) content to following;
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('gamereview/', include('gamereview.urls')),
]

Ckeditor/ django 2.0 admin body input disappeared

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.

django-recommend not running the crontab

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.

Categories