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"
Related
I have a ModelChoiceField and a ChoiceField that I need to pull out the "display name" for (not the "value").
For example, a ModelChoiceField of a form renders the following output:
<select name="amodelfield" id="id_amodelfield">
<option value="">---------</option>
<option selected="selected" value="1">ABC</option>
<option value="2">DEF</option>
</select>
I want to be able to just render "ABC" since it is selected. If I do {{ field.value }} as said in the docs, I get the value 1 instead of the ABC I wanted. I also have a ChoiceField for which I want the same behavior.
Is there a easy way to do this without subclassing ModelChoiceField, ChoiceField and the Select widget?
EDIT: Model.get_FOO_display() would not work in this case
Use {{ get_fieldname_display }} for it.
https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display
From the link that #Odif Yltsaeb provided, I was able to use modify the code from the answer to work generically for my needs. Here's the code for reference:
def choiceval(boundfield):
"""
Get literal value from field's choices. Empty value is returned if value is
not selected or invalid.
Important: choices values must be unicode strings.
choices=[(u'1', 'One'), (u'2', 'Two')
Modified from:
https://stackoverflow.com/a/5109986/2891365
Originally found from:
https://stackoverflow.com/questions/19960943/django-rendering-display-value-of-a-modelchoicefield-and-choicefield-in-a-templ
"""
# Explicitly check if boundfield.data is not None. This allows values such as python "False"
value = boundfield.data if boundfield.data is not None else boundfield.form.initial.get(boundfield.name)
if value is None:
return u''
if not hasattr(boundfield.field, 'choices'):
return value
return dict(boundfield.field.choices).get(value, u'')
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
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...
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.