Django Forms: En-/Disable a Charfield dynamically - django

i have a form with a ChoiceField and a CharField. Now i want to enable the CharField just when i select a specific choice of the ChoiceField (e.g. choice 3). Otherwise the CharField should be disabled.
My ChoiceField
choices = (('1', 'some text',),
('2', 'some text',),
('3', 'some text',))
host = forms.ChoiceField(choices = choices)
And a simple CharField
hostAdress = forms.CharField()
Do you have any ideas to get it this way?

you can start with the char field disabled/hidden and use javascript to catch change event on the select box and change the charfield on that event. For example:
$("#id_choice").change(function(eObj) {
$("#id_char").removeAttr("disabled");
this is just an example (using jQuery), you need to make sure to disable the charfield again if the select box is unselected (not sure if you allow this behaviour) and you also need to handle the display of form errors properly if you hide the field and not enable/disable it.

I would use jQuery for this.
$('your-select-input-selector').change(function() {
var bDisable = true;
if ($(this).val() == '3'):
bDisable = !bDisabled;
$('your-text-input-selector').prop('disabled', bDisable);
});
You also need to handle the case where the select input is already set on the value 3 when you first load the page.

Related

Django forms.SelectMultiple complains about choices

I'm trying to create a form consisting of a multiple select field which is used to select multiple instances of my Person model.
class MyForm(forms.Form):
choices = [(p.id, str(p)) for p in Person.objects.all()]
my_field = forms.ChoiceField(widget=forms.SelectMultiple, choices=choices)
The widget looks exactly like I want, but when I submit the form, it fails with the message
Select a valid choice. ['2', '3'] is not one of the available choices.
What am I doing wrong? When removing the widget=forms.SelectMultiple, from the third line, it works, but then it's only a single select field.
You are getting the error because ChoiceField expects a single choice.
If you want to allow multiple choices, use a MultipleChoiceField.
my_field = forms.MultipleChoiceField(choices=choices)
Note you don't have to specify the widget, as it's forms.SelectMultiple by default.

Django Admin Radio Buttons

Looking for a way to use radio buttons in the Django admin. I would like to have 3 or 4 hard coded options the user can select from and I will use that selection to know what to do with the next text field. The options never need to change. Can anyone point me in the right direction? Google is not cooperating on this one...
I'm going to assume you want this on the change page for a Foo model object. Let's call the extra field my_option.
First, you'll need to use a custom form in your FooAdmin class so you can get the extra field in there:
class FooAdmin:
...
form FooForm
fields = (..., 'my_option', ...)
...
Then, just create the form with the extra option:
class FooForm(forms.ModelForm):
class Meta:
model = Foo
my_option = ChoiceField(
label = 'Options',
choices = (
(0, 'Don\'t change anything.'),
(1, 'Do some crazy stuff.'),
(2, 'Do other stuff.'),
),
initial = 0,
widget = RadioSelect,
)
ChoiceField defaults to using a select box, which is why you also need to override the widget type in the field's constructor. You can also check out TypedChoiceField if that serves your needs better.
Finally, you'll need to handle the field somewhere. I suggest overriding the clean() method in FooForm to get the value and set values in self.cleaned_data depending on what you want the option to do.

django - Creating a radio select with select box options

I want to create a set of radio options that look like so:
The non-standard part is that selecting the first or second radio button option requires the user to further specify information from a select box.
How do I do this with a django form? Based on what I see in the docs you can pass a Choices 2-tuple with only strings as the human-readable values, I need the ability to pass a widget plus a label. I am rendering the form via django-crispy-forms in the template (i.e. all my template has is {% crispy form %}), so I would prefer a solution that doesn't require any template-side manipulation.
Thanks!
in forms.py
CHOICES = (('0', 'option1',), ('1', 'option2',), ('2', 'option3',))
class NameForm(forms.ModelForm):
options = forms.ChoiceField(initial=0, widget = forms.RadioSelect(renderer = HorizontalRadioRenderer), choices=OPTIONS)

Null field in select dropdown

How do I get rid of the Null choice in a select dropdown? For example, I have the following model --
class Network(models.Model):
type = models.CharField(max_length=10, choices = [('closed','closed'),('open','open')])
When I use the form in the template, I get three choices in the dropdown:
-------
Closed
Open
How do I get rid of this Null choice? So the select dropdown will only have the Closed and Open options?
From the documentation (via):
By default the widget used by ModelChoiceField will have an
empty choice at the top of the list. You can change the text of this
label (which is "---------" by default) with the empty_label
attribute, or you can disable the empty label entirely by setting
empty_label to None
Set blank=False in your model.
From the documentation:
Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.
choices = [("","-- Select an option --"),('closed','closed'),('open','open')]

ChoiceField or CharField in django form

I have a CharField in the model that needs to be selected by a ChoiceField. If the user's choice is not in the choice field then they'd select "other" and be able to type in a text input. How can I do this? I don't need the javascript; just the help with the django part.
The best approach is to have just a CharField in your models/forms with a custom widget to display your choices and 'other' with the right behavior.
RZ has a good solution
An alternative solution (with less javascript) is to have a hidden "other" CharField that is made visible when the "Other" option is selected on your ChoiceField
edit: Hidden as in style="display: none;" not a HiddenInput field
something like (with jQuery):
$("#id_myChoiceField").change(function() {
if ($(this).val() == 'other') {
$("#id_myOtherInput").show();
}
else {
$("#id_myOtherInput").hide();
}
});
You'll have to write your own validation code though and set required=False on the "Other" Charfield
Your class for that form should look something like this:
class ChoicesForm(forms.ModelForm):
# some other fields here
...
other = forms.CharField(required=False)
...
Just create a javascript that displays the 'other' text input if the user chooses 'other' among the choices.