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.
Related
I am trying to upload videos to my Django server directory. When I use the coded app in the admin panel, upload succeed at the correct location. However, when dealing with browser form, it will miss a level of the url as : 'media/title.mp4' instead of 'media/videos/title.mp4.
I'd like to save the files into 'media/videos/title.mp4'. Currently, front uploaded videos url is computed as 'media/title.mp4. It just fails, no resources created, even at the wrong location.
Here is my urls.py with the upload route :
from django.urls import path
from uploader.views import upload, download
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('upload/', upload, name='upload'),
path('download/', download, name='download'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my upload view :
from django.shortcuts import render, redirect
from .models import VideoItem
def upload(request):
if request.method == 'POST':
title = request.POST['title']
video = request.POST['video']
content = VideoItem(title=title, video=video)
content.save()
return render(request, 'upload.html')
Here is my upload html template :
<form action="" method="POST">{% csrf_token %}
<input type="text" name="title" placeholder="Enter Video Title here"><br>
<input type="file" name="video" accept="video/mp4">
<button type="submit"> Upload New Video </button>
</form>
And here is my db model :
from django.db import models
# Create your models here.
class VideoItem(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='videos')
class Meta:
verbose_name = 'video'
verbose_name_plural = 'videos'
def __str__(self):
return self.title
My media root / directory config (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__)))
# 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 = someSecretKey
# 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',
'uploader.apps.UploaderConfig',
]
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 = 'pixblur_project.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 = 'pixblur_project.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 FILES (OPTIONAL)
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
# MEDIA FILES
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Any hints?
You should be using request.FILES not request.POST to access uploaded files. See more here.
def upload(request):
if request.method == 'POST':
title = request.POST['title']
video = request.FILES['video'] #<-- change it here
content = VideoItem(title=title, video=video)
content.save()
return render(request, 'upload.html')
As datosula mentioned, request.FILES fits here. However, to be able to get the ressource to write to the right directory with the right data (aka. request.FILES not being empty), i had to add the attribute enctype="multipart/form-data"> to my form.
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
This has been driving me crazy for 2 days now and I cannot find an answer to this. I have looked through countless posts and cannot get this to work.
I am trying to display a profile picture for a user using Django ImageField in my model.
For some reason it keeps on coming up with 404 not found, even though I can see that the path to the image file is correct.
For example:
My model:
class KPILead(models.Model):
name = models.CharField(max_length=255)
position = models.CharField(max_length=255)
company = models.ForeignKey(KPICompany)
profile_pic = models.ImageField(upload_to='profile_pics/')
def __str__(self):
return self.name
This is indeed uploading the image file to the media/profile_pics folder in my root directory.
The view:
#login_required(login_url='/')
def eftlead_detail(request, eftlead_id):
context = dict()
context['eftlead'] = KPILead.objects.get(pk=eftlead_id)
context['team_names'] = KPITeam.objects.filter(eft_lead__id=eftlead_id)
context['incidents'] = KPIIncidentReport.objects.filter(eft_lead__id=eftlead_id)
context['image_url'] = context['eftlead'].profile_pic.url
return render(request, 'templates/eftlead.html', context)
The static and media settings in my settings file:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
And I have added:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
to my urls file.
It just gives an error of 404 not found, even when I check the source in Chrome or Firefox I can see that correct path is being shown. If I try and click on the image in the source to go to http://127.0.0.1:8000/media/profile_pics/default.jpg I get an error of 404 not found, so Django is clearly not finding the file even though the path is correct.
As I said I have struggling with this for 2 days now and is probably the last thing I need to finish this project off, but I cannot understand what is going wrong.
I would happy to provide further information if required and thank you for any help.
EDIT: I have included my full 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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q#-jd#zkg7+#2-=6pjy(%vg-%=sh%c1*c%ypu&uxz0-4cm-9^p'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
USE_DJANGO_JQUERY = 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',
'base.apps.BaseConfig',
'projects.apps.ProjectsConfig',
'kpi.apps.KpiConfig',
'smart_selects'
]
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 = 'gregweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates', 'kpi'],
'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 = 'gregweb.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
}
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 = 'Africa/Johannesburg'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
LOGIN_REDIRECT_URL = '/kpi'
LOGOUT_REDIRECT_URL = '/'
Add this in your project's urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #not both
after searching for a solution for hours which did not resolve my problem,I am posting this. The image from my media root is not showing up on my html. In chrome's console i get a 404 file not found.Even though the image is there. I am using Python 3 ,Django 1.10 in Pycharm.
This is the model which is where i upload images to:
from django.db import models
class Post(models.Model):
username = "anonymous"
post = models.ImageField(upload_to='anon')
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return Post.username
views.py:
from django.shortcuts import render,get_object_or_404
from .models import Post
def home(request):
return render(request,"base.html",{})
def post_detail(request,id=None):
instance = get_object_or_404(Post,id=id)
context = {
"post": instance.post,
"instance": instance
}
return render(request,"post_detail.html",context)
post_detail.html(here the image isnt showing):
<body>
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
{{ instance.creation_date }}<br>
{{ instance.username }}<br>
</body>
Parts of setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Post',
]
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 = 'Post.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'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 = 'Post.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'),
}
}
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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Post/media/')
What my directories look like:
It's a common mistake to mix up the static and media settings. In your case what you are actually dealing with is user uploaded MEDIA and not STATICs.
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
The settings that are most relevent are MEDIA_* settings described here
https://docs.djangoproject.com/en/1.10/howto/static-files/
But more importantly, in your dev sever you need to enable the delivery of MEDIA by adding
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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.