change forms.py widget dynamically with user input from dropdown field in Django - django

I am trying to make a coding webapp in which users can write choose language and write the code.For it I am using ace editor.Ace editor requires the "mode" variable to know the language and provide syntax highlighting.
So,I have made a dropdown and I want to set the value of "mode" as the value of the dropdown field.e.g. If the users choose C++ I want mode="c++".I have the following code but I can't think of how to do it.
forms.py
from django_ace import AceWidget
class notepadModelForm(forms.ModelForm):
Your_code = forms.CharField(widget=AceWidget(mode='python', theme='clouds'))
class Meta:
model=notepadForm
fields=['Title','Your_code','Separator']
models.py
class notepadForm(models.Model):
CHOICES=[('python','Python'),('Cplusplus','C++'),('c','C')]
Title=models.CharField(max_length=120,null=False,blank=False)
Separator=models.CharField(choices=CHOICES,max_length=10,default=";")
Your_code=models.TextField(null=True,blank=True)
I have searched for it and found some examples to dynamically add fields but modifying the widget I didn't found thats why I asked it here.

You can create dropdown using javascript and the modelist extension from ace
<script src=http://ajaxorg.github.io/ace-builds/src/ace.js></script>
<script src=http://ajaxorg.github.io/ace-builds/src/ext-modelist.js></script>
<script>
var modelist = ace.require("ace/ext/modelist")
var dom = ace.require("ace/lib/dom")
// using buildDom from ace, but any other method of constructing dom can be used here
var modePicker = dom.buildDom(["select", {
value: "ace/mode/text",
onchange: function() {
editor.setOption("mode", this.value);
}
}, modelist.modes.map(function(x) {
return ["option", {
value: x.mode
}, x.caption];
})
], document.body);
var editor = ace.edit(null, {
maxLines: 10,
minLines: 5
})
document.body.appendChild(editor.container)
</script>

Related

Django select2 with ModelChoiceField/ createTag (how to create a create new record)

How do I handle using select2 with ModelChoiceField, but enable adding a new record
I have the Select2 JS in place, and everything works well. I can use my queryset for the ModelChoiceField, and that works. However, if I try to add a new record all I get is the error "Select a valid choice. That choice is not one of the available choices". Which is true - in the view I tried to grab "ID 0" to then create a new record, but can't get past validation without the above error
Also, if I do get this to work, it will provide the "0" ID, but ultimately I require the "term" for the new record, but can't see how this is done
<script type="text/javascript">
$("#id_indoor_cooler").select2({
theme:"bootstrap4",
search_fields: ['model_number'],
tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: 0,
text: term,
newTag: true, // add additional parameters,
value: "myCustomValue"
}
}
});
</script>

Color rows when "group by" sharepoint 2013

I need some help. I'm trying to set color when group by in a sharepoint list.
I'm using the following code
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPostRender: function(ctx) {
var statusColors = {
'Liberada' : '#FFF1AD',
'Cancelada' : '#FFD800',
'Créditos' : '#01DF3A'
};
var rows = ctx.ListData.Row;
for (var i=0;i<rows.length;i++)
{
var status = rows[i]["Status"];
var rowId = GenerateIIDForListItem(ctx, rows[i]);
var row = document.getElementById(rowId);
row.style.backgroundColor = statusColors[status];
}
}
});
});
Can someone give a hint?
As I can see in my local Sharepoint 2013 environment, when I create a view with a group by, Sharepoint add a CSS class named « ms-gb » on the table cell that contains the group name.
Knowing this, a solution would be to edit the page of the view.
Then you can add to the page a Script Editor Webpart.
Inside this Script Editor Webpart you can add some JavaScript code to add the background-color.
Something like this for example :
<script>
$(document).ready(function(){
var statusNames = ['Liberada', 'Cancelada', 'Créditos'];
var statusColors = {
'Liberada' : '#FFF1AD',
'Cancelada' : '#FFD800',
'Créditos' : '#01DF3A'
};
$('td.ms-gb').each(function(){
for (var x=0;x<statusNames.length;x++) {
if ($(this).text().indexOf(statusNames[x]) > -1) {
$(this).css('background-color',statusColors[statusNames[x]]);
}
}
});
});
</script>
If you try this script and you don't already have a reference to JQuery in your masterpage or page layout, you will need to add one inside the script editor webpart.
You can download a local copy of JQuery or use one hosted like :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Hope this help.

How to remove events from nicEditor + emberjs

I am working on an Ember.js - based platform, where I use nicEdit. Here is my code
RichHTMLView = Ember.TextArea.extend({
id: null,
editor: null,
didInsertElement: function(){
var view = this;
view.id = this.get("elementId");
view.editor = new nicEditor({
buttonList : ['bold','italic','underline','right','center','justify', 'link', 'ul', 'ol']
}).panelInstance(view.id);
//When the editor looses focus the content of the editor is passed to descr
view.editor.addEvent('blur',function(){
view.get('controller').set('descr',view.getViewContent());
});
//So the editor looks nice
$('.nicEdit-panelContain').parent().width('100%');
$('.nicEdit-panelContain').parent().next().width('100%');
},
getViewContent: function(){
var view = this,
inlineEditor = view.editor.instanceById(view.id);
return inlineEditor.getContent();
},
willClearRender: function(){
var view = this;
}
});
So this works nicely as long as I am on the page which hosts the view, but if I transition to another route, the view has some leftovers, namely the editor is destroyed, but I assume that nicEdit keeps track of event bindings, so I end up with the blur event being bound to editor, which is undefined in the new context, as the view does not exist.
My best guess is that I need to somehow unbind the editor in the willClearRender, but I don't know how.
as I got no reply and nicEdit is abandoned I made some changes to the source-code in order to deal with this issue by adding removeEvent to bkEvent:
removeEvent: function(A, B){
if (B){
this.eventList = this.eventList || {};
this.eventList[A] = this.eventList[A] || [];
this.eventList[A].splice(this.eventList[A].indexOf(B),1);
}
Then I can remove the event in willClearRender:
view.editor.removeEvent('blur',view.onBlur);
Be aware that I've not tested it with multiple editors, as my needs do not require, but if you have multiple editors with the same callback the behavior is not defined.

How do I add custom HTML in Rally sdk 2.0?

I'm creating an app with some custom gauges using Rally SDK 2.0. This requires some custom HTML. I took a rake-compiled app.html file from the examples as a starting point. Using JustGage for my gauges. Here is my launch function.
launch: function () {
var info = this.getStoriesForProject(); //Gets some aggregate info
$('#header label').html(info.Title);
var g = new JustGage({
id: "devgauge",
value: info.DevPercent,
levelColors: ['#f80404', '#f8f804', '#50ed0e'],
min: 0,
max: 100,
title: "Dev %"
});
this.add('foo');
},
Then I added some custom HTML in app.html.
Now, if i run this without the code "this.add('foo')", the app adds a new div in the body with class="x-container" and puts my custom HTML outside that div effectively hiding it.
If i use the "this.add('foo') it does NOT create the div class=x-container and it shows my widget just fine.
What is the PROPER way to accomplish what I'm attempting using the 2.0 sdk? I realize the add method is for adding Ext components, but somehow calling this is causing my HTML to render ok. Looking at some apps we developed in the old SDK, using the custom HTML worked just fine in those.
Ext likes to know what is going on layout-wise and often gets confused if you're manually manipulating the dom beneath it without its knowledge. Usually if we have some known set of initial layout we add those via the items collection on the app:
Ext.define('My.App', {
extend: 'Rally.app.App',
items: [
{
xtype: 'container',
itemId: 'header'
},
{
xtype: 'container',
itemId: 'devguage'
}
]
});
Then inside of launch you can add content to those like so:
this.down('#devguage').add({
//some other component
});
You can always just drop all the way down to the element level though as well:
this.down('#header').getEl().dom //the raw html element
By default apps use an auto layout, so any items should flow as you would expect with normal html.
Or, instead of using itemId, you can set the id of the container's element using its id property:
Ext.define('My.App', {
extend: 'Rally.app.App',
items: [
{
xtype: 'container',
id: 'header'
},
{
xtype: 'container',
id: 'devguage'
}
]
});
The resulting html elements will use those ids, which allows you to target them directly with your own custom rendering.

Sencha Touch: XTemplate not visible in DataView

I'm a newbie to all the Sencha Touch stuff, but until now I'm very enthousiastic about it's capabilities. There is one problem, i somehow can't solve.
I would like to use a Tpl (XTemplate) for a calender view. The idea is to create a div element for every appointment, which i can place within containers to layout them. Somehow i can't get the dataview to work.
I've stripped down my code to the bare minimum: a panel containing a DataView. When i use the itemTpl, everything works fine. But when I use the tpl (with or without the XTemplate) i don't see anything. I checked if it was just a display malfunction (searched for the XXX from the template), but that's not the case.
This is my code:
Ext.define('InfoApp.view.CalendarDay', {
extend: 'Ext.Panel',
xtype: 'calendarday',
requires: [ 'InfoApp.store.sAppointments'],
config: {
title: 'Dag',
layout: 'fit',
items: [
{
xtype: 'dataview',
store: 'appointmentStore',
//itemTpl: [ 'XXX {day} {course}' ] --> Works
tpl: new Ext.XTemplate('<tpl for=".">XXX {day} {course}</tpl>')--> Doesn't Work...
}
]
}
});
Thanks in advance for any suggestions or improvements!
Assuming ST2 and not ST1
From http://docs.sencha.com/touch/2-0/#!/api/Ext.Component-cfg-tpl and the comments on the tpl: config in the docs, it appears there's a bug when using a remote store. Even if your store has data it. tpl: apparently only works right now if your data is hardcoded in data:[]
you can use itemTpl: new XTemplate(), or itemTpl: XTemplate.from('someid') or you can defer specifying until afterwards, grab your dataview and go dv.setItemTpl(new XTemplate()), etc.
Tanks #brink for your answer.
It took me a couple of days, but this worked for me:
// Load the store
var store = Ext.getStore('appointmentStore');
// Get the current range of the store
var data = store.getRange();
// Create a custom template
var tpl = new Ext.XTemplate(<tpl for=".">{day} {course}</tpl>);
// Loop through the data array
var showData = array();
for(var i=0;i<data.length;i++){
showData.push(data[i].data);
}
// Get the panel by ID and push the html template
var panel = Ext.getCmp('appointmentspanel');
panel.updateHtml(tpl.applyTemplate(showData));