Integrate calendar widget in Django app - django

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']

Related

Using Chosen.js with Django

Hello Im trying to implement chosen.js into my Django project and so far it works great. I only have one issue which I cannot solve. I have a model where "language" is a ChardField. I wanted to let the User choose more than one language so I tried to use chosen Multiple. Since a Charfield can only hold one Value so I used Django Multiselect. Now the Chosen.js is not working anymore and I have no idea what to do.
Models:
from multiselectfield import MultiSelectField
class UserProfile(models.Model):
language = MultiSelectField(verbose_name=_(u"Content Language"),
max_length=40, choices=settings.LANGUAGES,default='en')`
Forms:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields=[
'language',
.....
]
Template:
{% load widget_tweaks %}
{% csrf_token %}
<span>Content language {{ form.language|add_class:"chosen-select" }}</span>
So the question is how do I get the normal chosen.js input field to a multiple chosen field (with Django)? I know there is the possibility to add a multiple field to the forms but this messes up my hole code.
I implemented the chosen multi select by the following:
Forms
class select_language(ModelForm):
#Get data for choice boxes
language_results = language.objects.all()
select_language = forms.ModelMultipleChoiceField(
queryset=language_results,
widget = forms.SelectMultiple(attrs={
'placeholder': "Choose the users(s)",
'class': 'chosen-select',
'multiple tabindex': '4',
}),
)
Template:
....
{% load static %}
<link rel="stylesheet" href="{% static 'chosen.css' %}">
<link rel="stylesheet" href="{% static 'prism.css' %}">
....
{{ select_language.select_language }}
<script type="text/javascript" src="{% static 'chosen.jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/prism.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/init.js' %}"></script>
Of course you will need to update the locations for the static files. Hopefully this is a good starting direction.

page extension with tinyMCE django-cms

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'],
]
}

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'

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.