How to render default values in django-ajax_select field - django

I am using ajax_select for my m2m and foreign key fields, its working fine but it is not rendering default value of that field, it is rending empty value ("|").
I am not using ajax_select in my admin panel, so when I open that form in admin panel, fields are having default values already. That means their is no problem in default values but in ajax_select field.
What it is rending now :
<input type="hidden" name="colours" id="id_colours" value="|" data-ajax-select="autocompleteselectmultiple" data-plugin-options="{"source": "/ajax_select/ajax_lookup/colours", "html": true}" data-changed="true">
What I wanted is:
<input type="hidden" name="colours" id="id_colours" value="|8|" data-ajax-select="autocompleteselectmultiple" data-plugin-options="{"source": "/ajax_select/ajax_lookup/colours", "html": true}" data-changed="true">
If at least default value initialized in name=colour, I can show help text that default value is White.
As I searched at documentation of ajax_select but nothing found related to it, does anyone know how to render default values in ajax_select field.
Is this problem occurring with me only or ajax_select doesn't have this default value feature ?

This can be achieved by overriding the get_form() method as :
def get_form(self,form_class=None):
form = super().get_form(form_class)
form['colours'].initial = '8'
return form
Now default value is set manually and also working in ajax_select.

Related

How to change booleanfields using bootstrap switches?

I want to use the switch button on the bootstrap to operate the model called field, but I don't know how to access it.
class NewBlank(models.Model):
...
blank_on_off = models.BooleanField(default=False)
...
If I have the following booleanfield and can I change the booleanfield by cycling the switch as shown in the picture?
From the HTML specifications, the default value for a checkbox is "on" because you have not included a value attribute
default/on
On getting, if the element has a value attribute, it must return that
attribute's value; otherwise, it must return the string "on". On
setting, it must set the element's value attribute to the new value.
Change your html to
<div class="bootstrap-switch-square">
<input type="checkbox" data-toggle="switch" name="Resend" id="Resend" value="true" />
</div>
so that if its checked, a value of true will be sent in the form data and correctly bound to your boolean property (if unchecked, no value will be sent and the property will be its default (false) value
originaly answered

display any value from django views to html form input

I'm working on Django app and i have only one page in my templates directory named "index", everything is working well but i faced a problem when i wanted to display the result which will be passed by Django views to my HTML page. I want the value to be displayed on my input field instead of printing it on the browser. I searched a lot but i couldn't found anything related to this.
I have three fields:
key field.
Plaintext field.
Ciphertext field.
and one button for encryption & decryption.
I need when i click on the button, the result will be displayed on my Ciphertext field not on the browser because i already did that before.
Can you help me?
Thanks..
One of the multiple ways is to,
render the template from view.
pass the values for "key field" and "plain text filed" into the context variable (ex: return render(request, context={'key_filed': key_field_value, 'plain_text_field': plain_text_field_value} ).
Use these values in "value=" field of < input > tag. (ex: < inpu type='text' value={{ key_filed }} > and < inpu type='text' value={{ plain_text_field }} >)

Hiding ModelMultipleChoiceField on template for custom input

I want the user to select a number of elements belonging to a certain model. I don't want to use the default 'ctrl+click' input of django forms, but create a table of checkboxes myself.
For that reason I hide the ModelMultipleChoiceField by defining the widget:
field = forms.ModelMultipleChoiceField(..., widget=forms.MultipleHiddenInput())
Then I add the form element into the template as follows:
<form method="POST" class="locklist-form" id="locklist-form">{% csrf_token %}
{{ form.field }}
</form>
At this step, I expect the select-option elements to be added to HTML page (as hidden), so that I can reach to element options and modify them with javascript. However, it doesn't add anything to the HTML page.
I use this approach with other type of form fieds. For a TextField HTML page have a hidden element as shown:
Why doesn't it work with ModelMultipleChoiceField? How can I modify the choices of this field with Javascript?
Edit:
MultipleHiddenInput renders only if with initial data is a similar question. But applying it doesn't lead to the expected solution. In this question, it is expected to render the following as hidden:
But following the MultipleHiddenInput renders only if with initial data, when I modify the form constructor as:
form = MyForm(initial={'field':MyModel.objects.all()})
Rendered element is as follows:
It maybe useful, but not exactly the expected one. I need to mark a few options as selected, among a list of objects.
I have done it using Javascript, instead of depending on Django's capabilities. I add the form with ModelMultipleChoiceField directly to the template (not hidden). Then I run a Javascript script, when the page is loaded:
var field = document.getElementById('id_field');
selecter.setAttribute('class', 'hidden');
CSS definition of hidden class is as follows:
.hidden{
display: none;
}
This gets me to the desired situation. ModelMultipleChoiceField is rendered hidden as follows:
At this point, I can modify certain items through Javascript:
document.getElementById('id_field').options[index].selected = boolValue;

Django: Rendering display value of a ModelChoiceField and ChoiceField in a template

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'')

Django forms: checkboxes are displayed without value

I'm unable to save my form (a ModelForm) properly, since django displays checkboxes without a value (I would expect value="true" on every fields, both checked than unchecked... but that's not the case).
When I submit the form, no data is received in the POST!
The following is a piece o my template:
<div>
{{form.displayAge.label_tag}}
{{form.displayAge}}
{{form.displayAge.errors}}
</div>
{{form.displayAge}} is rendered in this way:
<input checked="checked" type="checkbox" name="displayAge" id="id_displayAge">
BUT... since it has no value, checking/unchecking the checkbox is helpless! What should I do?
I would like to avoid typing form fields by hand!
No, there is no need for a value field. If the checkbox is checked, the browser will submit "on" as the value by default if none is supplied.
If you're not getting this value in your view, something else is wrong. Note that since you're using Django forms, you shouldn't be checking request.POST manually anyway: use form.cleaned_data.