page extension with tinyMCE django-cms - django

Hi everyone I create a page Extension using the documentation of Django CMS and work perfectly,
Now I have a two text_area in my extension page, I want to include TinyMCE library to my text_area
for this I have this in my models.py
from django.db import models
from cms.extensions import PageExtension
from cms.extensions.extension_pool import extension_pool
class IconExtension(PageExtension):
image = models.ImageField(upload_to='icons', blank=True)
description_short = models.TextField(blank=True, null=True, verbose_name="Short Description")
description_large = models.TextField(blank=True, null=True, verbose_name="Large Description")
extension_pool.register(IconExtension)
and my admin.py have this
# from django.forms import *
from django.forms import ModelForm
from django import forms
from django.db.models import *
from django.contrib import admin
from cms.extensions import PageExtensionAdmin
from tinymce.widgets import TinyMCE
from .models import IconExtension
class IconExtensionForm(forms.ModelForm):
some_field = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 10}))
class Meta:
model = IconExtension
fields = '__all__'
class IconExtensionAdmin(PageExtensionAdmin):
form = IconExtensionForm
admin.site.register(IconExtension, IconExtensionAdmin)
right now I obtain this error
jquery.tinymce.min.js:1 Uncaught TypeError: Cannot read property 'fn' of undefined(anonymous function) # jquery.tinymce.min.js:1(anonymous function) # jquery.tinymce.min.js:1
init_tinymce.js:16 Uncaught ReferenceError: tinyMCE is not defined
my setting.py file have this configuration
TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/jquery.tinymce.min.js")
TINYMCE_JS_ROOT = '/static/js/tinymce/'
TINYMCE_DEFAULT_CONFIG = {
'plugins': "table,spellchecker,paste,searchreplace",
'theme': "advanced",
}
TINYMCE_SPELLCHECKER = True
I look for the solution in internet and everybody say that I load the jquery library before... in my case my field with TinyMCE is inside of popup, the page have load the popup have the jquery Library in second time.. bootstrap is the first.
When I inspect the element inside the popup, my load library are this
<head>
<title>
Change icon extension | Django site admin</title>
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css">
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css">
<!--[if lte IE 7]><link rel="stylesheet" type="text/css" href="/static/admin/css/ie.css" /><![endif]-->
<script type="text/javascript">window.__admin_media_prefix__ = "/static/admin/";</script>
<script type="text/javascript">window.__admin_utc_offset__ = "\u002D18000";</script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="/static/djangocms_admin_style/css/djangocms-admin.css">
<script src="/static/djangocms_admin_style/js/dist/bundle.adminstyle.min.js"></script>
<script type="text/javascript" src="/en/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.js"></script>
<script type="text/javascript" src="/static/tinymce/jquery.tinymce.min.js"></script>
<script type="text/javascript" src="/static/django_tinymce/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/static/django_tinymce/init_tinymce.js"></script>
<meta name="robots" content="NONE,NOARCHIVE">
</head>
any idea how to include tinyMCE in page extension, I am in the right way?

Unless there is specific requirement to use TinyMCE, I would recommend using integration that is already built into the Django CMS Text module (CKEditor).
# models.py
class Model1(models.Model):
text = HTMLField(configuration='CKEDITOR_SETTINGS_MODEL1')
class Model2(models.Model):
text = HTMLField(configuration='CKEDITOR_SETTINGS_MODEL2')
# settings.py
CKEDITOR_SETTINGS_MODEL1 = {
'toolbar_HTMLField': [
['Undo', 'Redo'],
['ShowBlocks'],
['Format', 'Styles'],
['Bold', 'Italic', 'Underline', '-', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
]
}
CKEDITOR_SETTINGS_MODEL2 = {
'toolbar_HTMLField': [
['Undo', 'Redo'],
['Bold', 'Italic', 'Underline', '-', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
]
}

Related

CSS not applying to HTML page when receiving a new render in Django

I am currently struggling on a problem of HTML response.
I have an HTML page with CSS,JS working fine, the user will do an interaction that will go to JS -> send ajax request and do some treatment within a working view. And this view give me back a rendered view with all the info updated.
The problem is that the HTML given is containing everything but looks like "raw" HTML a.k.a no CSS applied to it, (scripts are working fine)
In the head of my HTML file :
<head>
<meta charset="utf-8">
<title>Sorting video: {{video.title}}</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'modelReco/cssFiles/swipeFrames.css' %}?v=00002'">
<script type="text/javascript" src='{% static "modelReco/jsScript/swipeFrames.js" %}?v=00003'></script>
</head>
The view that render the HTML:
def sendSortVideoResponse(request,untreatedFrame,myVideo,frames,tracks,url):
response = render(request, url, {
'video':myVideo,
'frames':frames,
'tracks':tracks,
'untreatedFrame': untreatedFrame[0],
'countTreated': untreatedFrame[1],
'totalFrames': len(frames),
'progressBar': untreatedFrame[1]/len(frames)*100,
})
response["Cache-Control"] = "no-cache, no-store, must-revalidate"
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
return response
In settings.py :
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
If you F5 the page then everything works fine again.
For the user, the page he is on doesn't reload so it might be the problem but I have an other stylesheet doing a progressing bar working perfectly so I'm confused.
So it might be a bad use of static files
EDIT Network and page :
Before the interaction :
After the interaction :
EDIT 2 : The rendered HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sorting video: fashionShow2</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" type="text/css" href="/static/modelReco/cssFiles/swipeFrames.css?v=00002'">
<script type="text/javascript" src='/static/modelReco/jsScript/swipeFrames.js?v=00003'></script>
</head>
<body>
<h1>Video: fashionShow2</h1>
<p>What can you do on this page?</p>
<p>You've chosen to sort the video fashionShow2, this means you want to help the A.I to recognize the model by simply clicking on the models and validate your answer</p>
<div id = 7951 class = "untreatedFrame" style="zoom:.6;-o-transform: scale(.6);-moz-transform: scale(.6)" >
<img class = "frameImg" src="/media/fashionShow2/frames/7951.png"/>
<a class = "frameImg" style="top: 0%; left: 65%; width: 35%; height: 100%;" onmouseover="displayValidation('rightCorner',true)" onmouseout="displayValidation('rightCorner',false)" onclick="validateFrameChoice(7951,1,true,'/modelReco/sortedTracks')">
<div id="rightCorner" class = "validationCorner"></div>
</a>
<a class = "frameImg" style="top: 0%; left: 0%; width: 35%; height: 100%;" onmouseover="displayValidation('leftCorner',true),true" onmouseout="displayValidation('leftCorner',false)" onclick="validateFrameChoice(7951,-1,false,'/modelReco/sortedTracks')">
<div id="leftCorner" class = "validationCorner"></div>
</a>
</div>
<div class="w3-container">
<div class="w3-light-grey w3-round-xlarge">
<div class="w3-container w3-blue w3-round-xlarge" style="width:73.01587301587301%">46/63</div>
</div>
</div>
<input type="button" value="Cancel previous choice" onclick="cancelPreviousChoice(7951)" />
<form action="/modelReco/">
<input type="submit" value="Return to home" />
</form>
<script>
</script>
</body>
</html>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (project not app)
from django.conf import settings
from django.conf.urls.static import static
...
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I found the issue on this problem. If you are trying to use ajax and render a new HTML by simply replacing everything with Jquery like I did ($("*").html(data);).
Be careful about applying CSS on your body element because browsers (as it is said on this post) usually don't care about those tags and remove it.
That's why in my retrieved ajax data, I had the body and everything but when rendered by the browser, the body tag was just disappearing.
If you need to apply CSS tags to body, just add a div tag like this and apply your css on it :
<body>
<div id="body">
....
</div>
</body>
The only weird thing is that when you F5 the page with Django the body tag come back, so the first look was ok but when rendered without refresh no body tag was showing.

trouble using tinymce in django

I am using django 1.6 and python 2.7. I am trying to integrate TinyMCE in django.I have included 'tinymce' in INSTALLED_APPS. Also, I included the tinymce in urls.py. While this works in admin, it doesn't work in templates.
my forms.py is
from django import forms
from .models import Question
from tinymce.widgets import TinyMCE
class QuestionForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80,
'rows': 30}))
class Media:
js = ('/static/js/tiny_mce/tiny_mce.js','',)
class Meta:
model = Question
fields = ('title','content','tags',)
Also, I included the js files in layout.html as follows:
<script type="text/javascript" src="{% static 'js/tiny_mce/tiny_mce.js' %}"></script>
<script type="text/javascript" src="{% static 'js/textareas.js' %}"></script>
the content of textareas.js is:
tinyMCE.init({
mode: "textareas",
theme: "simple"
});
Lastly, my page which uses tinymce is (ask.html) extending layout.html :
{{ form.media }}
{{ form.as_p }}
Any suggestion about where i am going wrong?

Django DateTimeField input Form

I have a DateTime field in my model and I'm looking for a simple way to make it look okay in the form. Something like the SelectDateWidget.
I've been looking at a lot of similar questions, and it seems really tricky to get something like the admin datepicker or jquery to work. (This is my first time using Django, and I have never used jquery before).
So, I'm using the ChoiceField instead from this example, but I can't get it to work either. I get error name 'self' is not defined. Can I not use self here? Or is there some better simple way to do this? I don't need a fancy datepicker, just something that makes the input easy for the user.
class ProjectForm(ModelForm):
startdate = forms.DateField()
starthour = forms.ChoiceField(choices=((6,"6am"),(7,"7am"),(8,"8am"),(9,"9am"), ...))
startminute = forms.ChoiceField(choices=((0,":00"),(15,":15"),(30,":30"),(45,":45")))
class Meta:
model = Project
def clean(self):
starttime = time(int(self.cleaned_data.get('starthour')),
int(self.cleaned_data.get('startminute')))
return self.cleaned_data
try:
self.instance.start_time = datetime.datetime.combine(
self.cleaned_data.get("startdate"), starttime)
except TypeError:
raise forms.ValidationError("")
forms.py
from django import forms
from django.contrib.admin import widgets
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
In template:
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
…or, for Django 1.4+:
{% load static %}
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/forms.css' %} "/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/base.css' %} "/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/global.css' %}"/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/widgets.css' %}"/>
<script type="text/javascript"
src="/admin/jsi18n/"></script>
<script type="text/javascript"
src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/jquery.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/actions.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/calendar.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/admin/DateTimeShortcuts.js' %}"></script>
If you're stuck with the error
Could not parse the remainder: '/js/jquery.init.js'' from 'admin/js/jquery.init.js''".
Just add an apstrophe before admin/js/jquery.init.js
it will look like:
'admin/js/jquery.init.js'

Integrate calendar widget in Django app

How do I integrate a calendar widget in my system? I wish to add the calendar widget to my form, which has been designed in Django. I'm attaching a screenshot showing where I want to integrate it. Also, I want the calendar widget to be like http://www.dynarch.com/projects/calendar/.
What file do I need to modify and what code do I need to use?
forms.py
import datetime
from django.forms.extras.widgets import SelectDateWidget
from django.forms import ModelForm, Form
date_field = forms.DateField(widget=SelectDateWidget)
or else there is also a another way using Javascript Using Django time/date widgets in custom form
it may be helpful
I figured it out. You just need to activate the admin interface in settings.py and import AdminDateWidget instead of SelectDateWidget in the forms.py file. Also, insert the following code into the template file of the form. Make sure to put it in between tags. here's the code:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
Hope its of use to somebody, cheers!
Saadat
After a long struggle, I managed to get it working for Django 2.0.2. You need the following in the header of template:
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
urls.py
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
...
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]
And then forms.py
from django import forms
from .models import MyModel
from django.contrib.admin.widgets import AdminDateWidget
class TripDetailForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
widgets = {
'my_field': AdminDateWidget(),
}
With this code, you must be good to go.
Just a tip for people who are using Django_filters and they want the admin calendar to show on there date fields (E.x Date is greater than) .. You need to declare the widget in the filter you created .
Like this :
class InterviewFilter(django_filters.FilterSet):
start_date = django_filters.DateFilter(name='date',lookup_expr=('gt'), widget=AdminDateWidget())
end_date = django_filters.DateFilter(name='date',lookup_expr=('lt'), widget=AdminDateWidget())
registry_year = django_filters.DateRangeFilter(field_name='date', lookup_expr='year')
class Meta:
model = Interview
fields = ['position', 'result', 'status']

Missing datepicker in Django 1.3 admin

Using Django 1.3, I am unable to see a datepicker for a Date or DateTime field in admin.
Model
Class xxxx:
departure_date = models.DateTimeField(verbose_name = 'Departure Date')
Admin
from django.forms import ModelForm
admin.site.register(models.Schedule)
settings.py
MEDIA_ROOT = "/mnt/django/project_green/media/"
MEDIA_URL = '/media/'
STATIC_ROOT = "/mnt/django/project_green/static/"
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
apache access.log
Seeing this weird 404 error
"GET /mnt/django/project_green/admin/jsi18n/ HTTP/1.1" 404 1159
source of admin page
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" />
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css" />
<!--[if lte IE 7]><link rel="stylesheet" type="text/css" href="/static/admin/css/ie.css" /><![endif]-->
<script type="text/javascript">window.__admin_media_prefix__ = "/static/admin/";</script>
<script type="text/javascript" src="/mnt/django/project_green/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js">
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
Thanks
George
I experienced the same problem: not being able to see date picker in django admin.
The cause of the problem was a bug in collectstatic command: https://code.djangoproject.com/ticket/15636
I ran collectstatic on Windows, and because of the bug, file /static/admin/js/admin/DateTimeShortcuts.js became lowercased: datetimeshortcuts.js
So when I deployed it on Linux to be served by Apache, link /static/admin/js/admin/DateTimeShortcuts.js gave 404 error.
Solution is simple: either migrate to Django 1.4 or run collectstatic on Linux.