I'm stuck in rendering a v2 form that I created using Preside formbuilder.
so far I have:
args.newsletter = formbuilderService.getForm("[id]");
args.rendered = formbuilderService.renderForm(
formId = args.newsletter.id,
layout = "default",
validationResult = "");
but all I get from args.rendered is:
<div class="formbuilder-form form form-horizontal"> <div class="alert alert-success"></div> </div>
But I want to render the whole form, like if I would add it by using a widget.
FormbuilderService.renderForm expects the configuration argument to contain data from the form builder widget in order to render the form correctly.
You can use the renderWidget helper to render the form
args.newsletter = formbuilderService.getForm( "[id]" );
args.rendered = renderWidget(
widgetId = "formbuilderForm"
, config = {
form = args.newsletter
, layout = "default"
, instanceid = ""
}
);
Related
Having trouble passing context variable to a django-component
View:
labels = "'January','February','March','April','May','June'"
data = "69, 10, 5, 2, 20, 30"
colors = "'#3e95cd', '#8e5ea2','#3cba9f','#e8c3b9','#c45850','#a45350'"
context = { 'title': title, 'language': langCode, 'clabels':labels, 'cdata':data, 'ccolors':colors}
return render(request, "reports/dashboard.html", context)
In Template:
<div class="col-lg-6">{% component "simplechart" width="980" height="300" chartid="chart1" title="We are testing" clabels='{{ clabels }}' cdata="{{ cdata }}" ccolors="{{ ccolors }}" type="bar" %}</div>
Components.py
#component.register("simplechart")
class SimpleChart(component.Component):
# Note that Django will look for templates inside `[your app]/components` dir
# To customize which template to use based on context override get_template_name instead
template_name = "simplechart/simplechart.html"
# This component takes three parameters
def get_context_data(self, width, height, chartid, title, clabels,cdata,ccolors, type):
print("CHART GET CONTEXT")
print(cdata)
print(clabels)
return {
"width": width,
"height": height,
"chartid": chartid,
"title": title,
"clabels": clabels,
"cdata": cdata,
"ccolors": ccolors,
"type": type
}
class Media:
css = {
'all': ('css/simplecard.css')
}
js = 'js/cmx_chart.js'
The debug print statements output:
CHART GET CONTEXT
{{cdata}}
{{clabels}}
It is passing in the litereal string, not replacing with context variable passed in from the view. Any ideas what I'm doing wrong?
The problem is that you are passing a string: "{{ clabels }}". Delete the quotes and the "{{" inside the tag. So:
{% component "simplechart" width="980" height="300" chartid="chart1" title="We are testing" clabels=clabels cdata=cdata ccolors=ccolors type="bar" %}
I don't understand how I can set up several Bokeh Chart in my django template. I have read this page https://docs.bokeh.org/en/latest/docs/user_guide/embed.html which supposed to explain this but it is not clear at all.
Here is my view :
def Bokehplot(request):
source = ColumnDataSource(S.df)
p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6)
q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6)
plots = {'Red': p, 'Blue': q}
script, div = components(plots)
return render(request, 'batterie/results.html', locals())
{{div|safe}} gives the 2 divs on a row. I would like to access div1 (first graph) and div2 (second graph) in order to put them in 2 different bootstrap columns ? Any help is welcome. Thanks!
Got my answer, very simple. My View :
def Bokehplot(request):
source = ColumnDataSource(S.df)
p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6)
q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc")
q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6)
plots = {'Red': p, 'Blue': q}
script, div = components(plots)
div1 = div["Red"]
div2 = div["Blue"]
return render(request, 'batterie/results.html', locals())
My template :
<div class = "row">
<div class = "col-sm-6 p-3 text-center">
{{ div1 | safe }}
</div>
<div class = "col-sm-6 p-3 text-center">
{{ div2 | safe }}
</div>
</div>
Now, I can arrange my plots with Bootstrap. Cool !
I have a view on my website that uses a couple of Django forms to allow the user to specify a date range. I was able to get it so that one Django form creates a start and end field and that when the user clicks on those fields a calendar widget (from here) pops up that allows the user to select a date range. However, when the user selects the date range and hits "apply" the form fields aren't updated.
EDIT
The form I'm using looks like this:
class DateRangeForm(forms.Form):
def __init__(self, *args, **kwargs):
initial_start_date = kwargs.pop('initial_start_date')
initial_end_date = kwargs.pop('initial_end_date')
required_val = kwargs.pop('required')
super(DateRangeForm,self).__init__(*args,**kwargs)
self.fields['start_date'].initial = initial_start_date
self.fields['start_date'].required = required_val
self.fields['end_date'].initial = initial_end_date
self.fields['end_date'].required = required_val
start_date = forms.DateField()
end_date = forms.DateField()
The view they are used in looks like this:
def table_search(request):
initial_start = "2015/2"
initial_end = "2015/222"
message = {'last_url':'table_search'}
if request.method == "POST":
daterange_form = DateRangeForm(request.POST,required=True,initial_start_date=initial_start,initial_end_date=initial_end)
else:
daterange_form = DateRangeForm(required=True,initial_start_date=initial_start,initial_end_date=initial_end)
search_dict.update({'daterange_form':daterange_form})
return render(request, 'InterfaceApp/table_search.html', search_dict)
The Django template here:
<div class="container">
<form action="/InterfaceApp/home/" method="post" class="form">
{% csrf_token %}
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
{% bootstrap_form daterange_form %}
<i class="icon-calendar icon-large"></i>
</div>
</div>
</form>
</div>
<script>
// the start_date and end_date are the ids that django form fields created
$("#daterange").daterangepicker({
locale: {
format: 'YYYY-MM-DD'
},
startDate: '{{daterange_form.start_date.value}}',
endDate: '{{daterange_form.end_date.value}}'
});
</script>
EDIT 2
And the forms currently look like this (after #ShangWang suggestion) rendered:
Is there a way to display it so the start and end date fields show up? I tried changing the div class so it wasn't hidden, and then they showed up but seemed superfluous.
I use bootstrap-daterangepicker: https://github.com/dangrossman/bootstrap-daterangepicker. It would bind the widget's change to your django form field, so you don't need to manipulate the data once it comes to the views.py.
To get more details you should download and play with it, but here's a rough idea:
Your form.py:
class DateRangeForm(forms.Form):
start_date = forms.DateField()
end_date = forms.DateField()
def __init__(self, *args, **kwargs):
# initialize the start and end with some dates
Your template:
<div class="daterangepicker-container mcast-search-filter">
<div class="daterangepicker-label">Date range:</div>
<div id="daterange" class="daterangepicker-content">
<i class="icon-calendar icon-large"></i>
<span></span> <b class="caret"></b>
</div>
</div>
<!-- This is a hidden div that holds your form fields -->
<div class="hide">From {{ daterange_form.start_date }} to {{ daterange_form.end_date }}</div>
To trigger the widget you need a javascript binding:
// the id_start_date and id_end_date are the ids that django form fields created
$("#daterange").initDateRangePicker("#id_start_date", "#id_end_date");
I created a datepicker wrapper, and defined the initDateRangePicker function. You should put following code in a file called daterangepicker.js and import that in your template as well(or simply copy it into your template):
(function($) {
$.fn.initDateRangePicker = function(start_date_el, end_date_el, future) {
return this.each(function() {
var start = moment($(start_date_el).val());
var end = moment($(end_date_el).val());
var display_date = function(start, end) {
var str = ""
str += start.format('MMMM Do, YYYY');
str += " - ";
str += end.format('MMMM Do, YYYY');
return str;
};
$(this).find("span").html(display_date(start, end));
var self = this;
if(!future) {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Last 7 days': [moment().subtract('days', 6), moment()],
'Month to date': [
moment().startOf('month'),
moment(),
],
'Last Month': [
moment().subtract('month', 1).startOf('month'),
moment().subtract('month', 1).endOf('month'),
]
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
else {
$(this).daterangepicker({
format: 'YYYY-MM-DD',
timePicker: false,
ranges: {
'Next 7 days': [moment().add('days', 1), moment().add('days', 7)],
'Next month': [
moment().add('month', 1).startOf('month'),
moment().add('month', 1).endOf('month'),
],
},
}, function(start, end) {
$(start_date_el).val(start.format('YYYY-MM-DD'));
$(end_date_el).val(end.format('YYYY-MM-DD'));
$(self).find("span").html(display_date(start, end));
});
}
});
};
}).call(this, jQuery);
I am using a Rowexpander inside a ExtjsGrid. RowExpander's template has text area which is used to get values from the user.
Below is my code.How can I read the value
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.Template(
'<p><b></b><div class="abc"> <input type="textarea" id = "hans_" name ="hans_" value = "{comment}"</ div></p><p></p><p>{promptMsg}</p>'
),
listeners:
{
expand: function(ex, record, body, rowIndex){
},
collapse: function(ex, record, body, rowIndex){
}
}
});
Solved ...
Below is the solution
Give a dynamic names to textarea of template
'<p><b></b><div> <textarea rows="2" cols="100" id = "{qnNum}" name ="{qnNum}" > {comment} </textarea><b></b></ div></p><p></p>'
Read the values
document.getElementById(record.data.qnNum);
I try to display a custom list from my controller, but when I want to use the pagination,
it doesn't work: for example if I want to diplay 10 entries (params.max = Math.min(max ?: 10, 100)), in my gsp list view all entries are displayed in the same page. I also noticed that I have pagination but I when I use it, I still have all entries displayed.
My code
def user = User.findByLogin("John")
List MyList
switch (userView){
case "mylist":
params.sort="date"
params.order="desc"
params.max = Math.min(max ?: 10, 100)
MyList = DS.findAllByCpCreator(user,[params:params])
case ...
...
def DSList = MyList
def DSCount = MyList.size()
[DSInstanceList: DSList, DSInstanceTotal: DSCount,userView:userView]
In gsp view, I modified the pagination like this:
<div class="pagination">
<g:if test="${userView!=null}">
<g:paginate total="${DSInstanceTotal}" params="${[q:userView]}" />
</g:if>
<g:else>
<g:paginate total="${DSInstanceTotal}" />
</g:else>
</div>
In your action, you are passing findAll* a map of maps, it should be:
MyList = DS.findAllByCpCreator(user, params)
EDIT: actually your view tag is ok
For count, you should use: http://grails.org/doc/2.2.x/ref/Domain%20Classes/countBy.html
DSCount = DS.countByCpCreator(user)