I have a template:
...
<form action="/reportform/" method="post">
<p><label>Aircraft system:</label>
<br>{{ Querry.system }}
...
it looks like this
How can I set a Size option for this box? for example, 10.
Use the attrs attribute to define the size.
class MyForm(forms.Form):
system = forms.ChoiceField(choices=SYSTEM_CHOICES,
widget=forms.SelectMultiple(attrs={'size':'40'}))
Sometimes, it is useful to override the widget in the forms init method.
class MyForm(forms.Form):
<snip>
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['system'].widget = forms.SelectMultiple(attrs={'size':'40'}))
Related
class MyForm(Form):
real = BooleanField()
If MyForm(data={'real': 'on'}), I want to render <input type="checkbox" checked=checked data-initial='on'>.
If MyForm(data={}), I want to render <input type="checkbox">.
How to achieve this?
You need to overwrite init of MyForm class:
from django import forms
class MyForm(forms.Form):
real = forms.BooleanField()
def __init__(self, *args, **kwargs):
data = kwargs.pop('data')
super(MyForm, self).__init__(*args, **kwargs)
if data != {} and 'real' in data:
self.fields['real'] = forms.BooleanField(initial=True, widget=forms.CheckboxInput(attrs={'data-initial': data['real']}))
so if real is passed as key in data dict it will make real field initialy True (checked) and value will be pass to data-initial attr.
How can I prevent this from happening
A Django TextField is rendered as a HTML textarea.
Looking at this question, you could use style="resize: none;".
If you would like to add that in your views/form (and not in the templates), you could try something like:
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['my_field_name'].widget.attrs['style'] = 'resize: none;'
or if you have a form instance
form.fields['my_field_name'].widget.attrs['style'] = 'resize: none;'
I'm trying to populate in my template a <select> element with data from a form field like this:
forms.py
class CreatePlayerForm(forms.Form):
size = forms.CharField()
views.py
class CreatePlayer(FormView):
...
def get(self, request, *args, **kwargs):
...
boots = Boots.objects.filter(...).values_list('size', flat=True) # return a list
form.initial['boots'] = boots
template
<select id="leftValues4" size="5" multiple>
{% for boot in form.boots %}
<option>{{ boot }}</option>
{% endfor %}
</select>
With the above code I don't get any results.
Any suggestion?
You are not approaching this in the right way at all.
initial is specifically for pre-setting the chosen value. You are trying to populate the list of values. For that, you will need to use an actual field that supports such a list; and that is a ChoiceField, not a CharField.
Secondly, choices need to have an ID value as well as a display value; so you need a list/tuple of 2-tuples.
form:
class CreatePlayerForm(forms.Form):
size = forms.ChoiceField(choices=[])
def __init__(self, *args, **kwargs):
sizes = kwargs.pop('sizes')
super(CreatePlayerForm, self).__init__(*args, **kwargs)
self.fields['sizes'].choices = sizes
view:
class CreatePlayer(FormView):
...
def get_form_kwargs(self, *args, **kwargs):
form_kwargs = super(CreatePlayer, self).get_form_kwargs(*args, **kwargs)
boots = Boots.objects.filter(...).values_list('id', 'size')
form_kwargs['sizes'] = boots
return form_kwargs
template:
{{ form.boots }}
I want to show empty form field if there is nothing to show, otherwise a form field with the value inside:
{% if somevalue %}
{{form.fieldname}} #<---- how do i set the `somevalue` as value of fieldname here?
{% else %}
{{form.fieldname}}
{% endif %}
In your view, if it is a class-based view, do it like so:
class YourView(FormView):
form_class = YourForm
def get_initial(self):
# call super if needed
return {'fieldname': somevalue}
If it is a generic view, or not a FormView, you can use:
form = YourForm(initial={'fieldname': somevalue})
There are multiple ways to provide initial data in django form.
At least some of them are:
1) Provide initial data as field argument.
class CityForm(forms.Form):
location = ModelChoiceField(queryset=City.objects.all(), initial='Munchen')
2) Set it in the init method of the form:
class CityForm(forms.Form):
location = ModelChoiceField(queryset=City.objects.all())
def __init__(self, *args, **kwargs):
super(JobIndexSearchForm, self).__init__(*args, **kwargs)
self.fields['location'].initial = 'Munchen'
3) Pass a dictionary with initial values when instantiating the form:
#views.py
form = CityForm(initial={'location': 'Munchen'})
In your case, I guess something like this will work..
class CityForm(forms.Form):
location = ModelChoiceField(queryset=City.objects.all())
def __init__(self, *args, **kwargs):
super(JobIndexSearchForm, self).__init__(*args, **kwargs)
if City.objects.all().exists():
self.fields['location'].initial = ''
else:
self.field['location'].initial = City.objects.all()[:1]
That all is just for demonstration, you have to adapt it to your case.
How to add:
onclick="this.form.submit();"
in my radiobutton form? I would like to post my form when user click to the radiobutton.
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.news = kwargs.pop('news')
super(MyForm, self).__init__(*args, **kwargs)
choices = ([ ("%s" % a.id, "%s" % a.text) for a in self.news])
self.fields['new'] = forms.ChoiceField(choices = choices, widget=forms.RadioSelect())
I would like to have this result in template:
<input type="radio" id="new" name="new" value="new" onclick="this.form.submit();">
self.fields['new'] = forms.ChoiceField(choices = choices, widget=forms.RadioSelect(attrs={'onclick': 'this.form.submit();'}))
while it's not the best idea to place template logic in your .py files.
How do you generate your form in a template?
If you use {{ form.as_p }} than consider rendering your custom form like described in: Django's Custom Forms