select choice from django model - django

Can i write ng-repeat to iterate through the choices in a Django model field and display them? How can i do it? Should I make a separate API for this or what?
APPROVAL_CHOICES = (
(u'Good condition', u'Good condition'),
(u'Bad condition', u'Bad condition'),
(u'Broken', u'Broken'),
)
status = models.CharField(max_length=20, choices=APPROVAL_CHOICES)
I have something like the following, but it's not working:
<label>Statuss</label>
<select>
<option value="" selected>--Please select Inventory statuss--</option>
<option value="inventory.status[0]" >Good Condition</option>
<option value="inventory.status[1]" >Bad Condition</option>
<option value="inventory.status[2]" >Broken</option>
</select><br/>
And here is my API:
objects: [
{
category: {},
count: 1,
created: "2014-02-24T16:07:12.903555",
description: "Car description for image",
id: 1,
location: "IT nodala",
name: "Baterija AA",
resource_uri: "/api/v1/inventory/1",
slug: "baterija-aa",
status: "Good condition"
},

using ng repeat like this
'<select data-ng-model="selectedField">' +
' <option data-ng-repeat="v in choices" value="v">v</option>' +
'</select> ' ;

I guess your question is about how to use select tag with angular js you can use the ngOption directive.
From the AngularJS docs:
ngOptions
The ngOptions attribute can be used to dynamically generate a list of elements for the element using the array or object obtained by evaluating the ngOptions comprehension_expression.
When an item in the menu is selected, the array element or object property represented by the selected option will be bound to the model identified by the ngModel directive.
...Note: ngOptions provides an iterator facility for the element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present.
with this jsfiddles:
<body ng-app="demoApp">
<div ng-controller="DemoController">
<div>
<h2>Incorrect</h2>
<p>
We might expect the select box to be initialized to "two,"
but it isn't because these are two different objects.
</p>
<select
ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options"
>
</select>
The value selected is {{ incorrectlySelected.value }}.
</div>
<div>
<h2>Correct</h2>
<p>
Here we are referencing the same object in <code>$scope.correctlySelected</code>
as in <code>$scope.options</code>, so the select box is initialized correctly.
</p>
<select
ng-model="correctlySelected"
ng-options="opt as opt.label for opt in options"
>
</select>
The value selected is {{ correctlySelected.value }}.
</div>
</div>
</body>
Check the docs form more exmaples.

Related

Django filters - adjusting box width

With django_filters, I have my filterset, everything works fine it's just the display that I am stuck with (box width).
As you can see below, I have changed the "size" attribute of some of the filter options - because the default is too wide. But the "rating" one, which is a NumberInput, doesn't work for some reason. The "size" attribute works for TextInput but not NumberInput.
I want to change the size or rather the width of the NumberInput box that will be displayed in the template (see template pictures below).
Can anyone help? Thanks in advance!
class ReviewFilter(django_filters.FilterSet):
comments = CharFilter(field_name='comments', lookup_expr='icontains', label="Comments ", widget=TextInput(attrs= {'size': 15 } ))
role_title = CharFilter(field_name='role_title', lookup_expr='icontains', label="Role title ", widget=TextInput(attrs={'size': 15 } ))
date_range = DateRangeFilter(field_name="date_created", label=" Posted date ")
**rating = CharFilter(field_name="rating", lookup_expr='gte', label="Minimum rating ", widget=NumberInput(attrs={'size': 1 } ))**
class Meta:
model = Review1
fields = '__all__'
exclude = {'recruiter', 'date_created', 'user'}
I have this:
Screenshot - Look at "Minimum rating" box width
But I want this:
Screenshot with filter search bar - Look at "Minimum rating" box width
I found a solution in the thread below by using the attribute - "style" : 'width6ch'
Apparently NumberInput doesn't have a working "size" attribute in HTML yet.
Solution to my problem
You cannot directly style the django-filters search fields. I was stuck with the same problem and here is my way of solving it.
Step 0 : intall widget_tweaks by pip install django-widget-tweaks
step 1 : add widget_tweaks to INSTALLED_APPS in your settings.py
step 2 : add {% load widget_tweaks %} into your template.html
step 3 : style individual elements in template
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.comments.label_tag }}
{% render_field filter.form.comments class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.role_title.label_tag }}
{% render_field filter.form.role_title class="form-control" %}
</div>
this way you can style individual form elements from filters, you can also add html tag attributes such as type or class and style them based on your needs.
you can use this link for reference. Link for Reference

datefield does not show today date in html form even if datetime.date.today is specified

I am using a datefied in my form and html form to render it. i want the date field to be non-editable todays date, but it shows the datepicker. Could anyone please help
model:
Dataset_Creation_Date = models.DateField(null=True, blank=True, default=datetime.date.today)
HTML:
<label for="field3"><span>Date of Dataset Creation <span class="required">*</span></span><input class="input-field" name="Dataset_Creation_Date" value="" type="date"/></label>
View:
Dataset_Creation_Date = request.POST["Dataset_Creation_Date"]
Remove type="date" to not get the date picker
Add readonly to just before the closing tag of the input.
Add a template variable to the value section of the input.
Format it to your specifications using date:"D d M Y". You can learn more about it from the documentation: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#date
The code which meets all your needs (subject to customization):
<label for="field3"><span>Date of Dataset Creation <span class="required">*</span></span><input class="input-field" name="Dataset_Creation_Date" value=" {{your_date|date:"D d M Y"}}"readonly></label>

How to preselect an option in an embedded HTML form?

I try to preselect an option of a select in an embedded HTML form in Camunda Tasklist, but always the first option is preselected.
I followed Binding to a Process Variable:
Binding to a Process Variable
A select box can be bound to a process variable using the cam-variable-name directive:
<select cam-variable-name="foo" cam-variable-type="String">
<option>bar</option>
<option>zar</option>
</select>
Research
I read also CAM-3173:
select box doesn't show the correct option
If I set the value of variable by a select box on the start form, the next task form didn't show the option that has been choosen in the start form. It uses the same select box.
but I use Camunda 7.9 and the problem is fixed since version 7.2.3.
HTML
<form>
<select cam-variable-name="variable" cam-variable-type="String">
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</form>
Result
option1 is preselected. I checked the process variable before entering the user task and it contains option2.
What did I wrong? If the bug still exists, is there any work-around?
I found a work-around, see Camunda Reference:
Implementing Custom Fields
The following is a small usage example which combines some of the features explained so far. It uses custom JavaScript to implement a custom interaction with a form field which does not use any cam-variable-* directives.
It shows how custom scripting can be used for
declaring a variable to be fetched from the backend,
writing the variable’s value to a form field,
reading the value upon submit.
[...]
The above example uses jQuery for interacting with the HTML controls. If you use AngularJS, you can also populate the $scope in the variables-fetched callback and read the values from the $scope in the submit callback:
My changed HTML:
<form>
<script cam-script type="text/form-script">
camForm.on('form-loaded', function() {
camForm.variableManager.fetchVariable('variable');
});
camForm.on('variables-fetched', function() {
$scope.variable = camForm.variableManager.variable('variable');
});
camForm.on('submit', function() {
camForm.variableManager.variableValue('variable', $scope.variable);
});
</script>
<select data-ng-model="variable">
<option value="option1">option1</option>
<option value="option2">option2</option>
</select>
</form>

Play framework select field empty value

How do I add a "none" option to the play framework select field?
So far, I have this:
<select size="1" name="object.id">
<option value="">&{'crud.none'}</option>
#{list items:someItems, as:'item'}
<option value="${item.id}">${item.name}</option>
#{/list}
</select>
but when i select the "none" value, play constructs a new object, and tries to save the parent object with a reference to the newly created object, resulting in a hibernate org.hibernate.TransientObjectException
Any ideas?
Set none option's value to 0 and in your controller add relation only in case if (item.id > 0)
<option value="0">&{'crud.none'}</option>
What's more if this value is required you can use simple check with JavaScript to ensure, that user selected some option

using get or post to pass argument to django view

In my django app ,I need to call a view with an argument named 'year'. Then in the template,I created a form and a dropdown list using a list of year names,At this point,I am confused as to how the view should be invoked.
The view is named 'create_report_for_data_of_the_year'.It expects a year argument.
ie,
http://127.0.0.1:8000/myapp/reports/2011
I tried to write the template as shown below.
<li id="yearlydataplots" class="report">
<form action="create_report_for_data_of_the_year" >
<select name="year" id="year">
{% for anyear in years %}
<option value={{anyear}} > {{anyear}}</option>
{% endfor %}
</select>
<input type="submit" value="Plot for entries of the year"/>
</form>
</li>
However,when the submit button is clicked,the browser goes to
http://127.0.0.1:8000/myapp/reports/create_report_for_data_of_the_year?year=2006
which causes a 404.
I changed method="post", and clicking submit goes to
http://127.0.0.1:8000/myapp/reports/create_report_for_data_of_the_year
which again causes 404
I know,I am missing something very basic :-)..If someone can kindly point it out,it would be nice
thanks in advance,
mark
def create_report_for_data_of_the_year(request,year,page_title,template_name):
dataset=MyDataModel.objects.filter(today__year=year,creator=request.user)
#today is a field in MyDataModel and is a datetime.datetime
map = create_map_of_names_and_values(dataset)
basefilename = "plotofdataforyear%s"%year
page_title = page_title+" "+year
imgfilename= create_plot(map,basefilename)
report_data={'basefilename':basefilename,'plot_image':imgfilename,'year':year,'page_title':page_title}
report_data["name_value_dict"]=map
req_context=RequestContext(request,context)
return render_to_response(template_name,req_context)
and url mapping is
...
url(r'^reports/(?P<year>\d{4})/$','myapp.views.create_report_for_data_of_the_year',
{
'template_name':'myapp/report_for_data_of_the_year.html',
'page_title':'report for data in the Year'
},name='report_data_for_year' ),
...
You need to do a redirect to desired page with JS. Or you can accept a year as a get paramener with year = request.GET.get('year').