I'm struggling for set the 'name' attribute of a form select field with django.
This is what i'm trying :
def make_layers_form(dxf_model):
layers = Layer.objects.filter(dxf_file=dxf_model)
choices = [(m[0], m[1]) for m in settings.MACHINING_CHOICES]
fields = {}
for l in layers:
if l.name.decode() == "0":
# Si le layer 0 existe on l'associe a la "Coupe"
init = settings.MACHINING_CHOICES["CUT"]
else:
# Par défaut on met la valeur "Aucun"
init = settings.MACHINING_CHOICES["NONE"]
fields[l.name] = forms.ChoiceField(choices=choices, initial=init,
widget=forms.Select(attrs={'name':dxf_model.filename+"_"+str(l.pk)}))
return type('LayersForm', (forms.BaseForm,), {'base_fields':fields})
When I watch to the 'name' attribute, it is not set as expected...
Furthermore I try to set a default value in some case, but it has no effect. Any ideas ?
Thanks for your help!
UPDATE
Here is an html example
<select name="0" id="3_0">
<option value="NONE">Aucun</option>
<option value="CUT">Coupe</option>
<option value="MARK">Marqueur</option>
</select>
...
<select name="0" id="4_0">
<option value="NONE">Aucun</option>
<option value="CUT">Coupe</option>
<option value="MARK">Marqueur</option>
</select>
Each select tag permits to bind some datas to 2 differents files previously uploaded
The value of the attribute 'name' comes from the value of label_tag if I am not wrong.
And the value of the label_tag is a data extracted from each file respectively.
Unfortunately two differents files can contain the same value, which is extracted for setting the attribute 'name'. This is my problem!
So I would define the attribute name of each select tag as it follows:
(filename)+"_"+(the value extracted from the file)
I don't know if my explanations are clear...
Do you know why what i'm trying is not working ?
Further more when I set the initial value, it has no effects...
Related
I have a simple django dropdown form. I want to grab the text instead of the value.
<select name="doctors" required="" id="id_doctors">
<option value="" selected="">---------</option>
<option value="3">sometext</option>
</select>
On selection I want to use the some text in the backend.
if 'bookAppointment' in request.POST:
print(request.POST['doctors'])
print(int(request.POST['doctors'])-1)
print(Profile.objects.filter())
this prints out the value 3 is there a way to just get some text out.
3
2
<QuerySet [<Profile: some>, <Profile: some>, <Profile: some text>]>
I set it up like so:
bookAppointment = BookAppointmentForm()
# Make sure I get active doctors and doctors who have a refresh_token
bookAppointment.fields['doctors'].queryset = Profile.objects.filter(Q(is_active=True)&Q(is_doctor=True))
context['bookAppointment'] = bookAppointment
Just change the value to your text, that way the text is passed through to POST instead of the value.
Otherwise you will need to add in some controls:
if self.request.POST['doctors'] == 3:
my_var = "sometext"
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.
Trying to write custom validation for select field in the form. in template orm is displayed as:
<select id="id_myselect" name="myselect">
<option value="" selected="selected">---------</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
forms.py
class SubmitForm(forms.ModelForm):
...
def clean_myselect(self):
data=self.cleaned_data['myselect']
if data == 'First':
do something
return data
Doesn't work I'm also try to get error on the page and I see that value is on the page.
Request information POST myselect u'1' but Local vars say value myselect <Myselect: First> Any help?
You need to compare on the data value of the select not the sting.
As you have pointed out the value for myselect is u'1' so you need to compare against that and not the string representation.
class SubmitForm(forms.ModelForm):
...
def clean_myselect(self):
data=self.cleaned_data['myselect']
if data == 1: # 1 not "First"
do something
return data
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
Without using Ajax is there a way to get the value of a selected item. So for example, if I have the below drop down list:
<select name="controllers" id="id_controllers">
<option value="" selected="selected">---------</option>
<option value="1">http://przemeklach.com/api/firstOrder/przemeksController</option>
<option value="5">http://przemeklach.com/api/zeroOrder/ronsController</option>
</select>
How would I get at the 'value' in my view. I know I can get the 'http://przemeklach.com/api/firstOrder/przemeksController' part via
controller = form.cleaned_data['controllers']
but I also need the 'value' in this case 1.
Thanks.
Scratch the old response (below), cleaned_data contains object references. You can get the ID by refering to model methods.
You can get the id from form.data['controllers'] but it needs sanity checking (in this case it should be an int). Of course if the is_valid() returns True it should be one of the ids available in the queryset you supplied when defining the field.