Django - Remove the Checkbox in ClearableFileInput widget - django

I'm finding it overly difficult to customize ClearableFileInput as set as the default widget in a modelForm that includes an ImageField in the model.
Particularly I don't want the Delete Checkbox that is part of the widget. I've tried customizing/overriding the rendering in a number of ways to get rid of the checkbox including setting the widget to FileInput and overriding the render method where subclassing the widget in a widgets.py file.
The simplest I can explain the problem is like this:
forms.py
class SpecImageForm(ModelForm):
orig_image = forms.ImageField(required=False, widget=forms.FileInput)
class Meta:
model = SpecImage
fields = ['orig_image',]
# The intention is to have more than one SpecImageForm once this is working but for now the
# max_num is set to 1
SpecImageFormSet = inlineformset_factory(Spec, SpecImage, form=SpecImageForm, extra=1, max_num=1)
Despite explicitly setting the FileInput against the widget it renders like this in my template - still including the checkbox which I don't think should be present using FileInput.
<fieldset>
<legend>Images</legend>
<input id="id_specimage_set-TOTAL_FORMS" name="specimage_set-TOTAL_FORMS" type="hidden" value="1" />
<input id="id_specimage_set-INITIAL_FORMS" name="specimage_set-INITIAL_FORMS" type="hidden" value="0" />
<input id="id_specimage_set-MAX_NUM_FORMS" name="specimage_set-MAX_NUM_FORMS" type="hidden" value="1" />
<ul>
<li>
<label for="id_specimage_set-0-orig_image">Orig image:</label>
<input id="id_specimage_set-0-orig_image" name="specimage_set-0-orig_image" type="file" />
</li>
<li>
<label for="id_specimage_set-0-DELETE">Delete:</label>
<input id="id_specimage_set-0-DELETE" name="specimage_set-0-DELETE" type="checkbox" />
<input id="id_specimage_set-0-id" name="specimage_set-0-id" type="hidden" />
<input id="id_specimage_set-0-car" name="specimage_set-0-car" type="hidden" />
</li>
</ul>
</fieldset>
The relevant part of the template is this:
<fieldset>
<legend>Images</legend>
{{ image_form.management_form }}
{% for form in image_form %}
<ul>
{{ form.as_ul }}
</ul>
{% endfor %}
</fieldset>
The only thing slightly different that I'm doing is using an inlineformset_factory.
I've also tried to override the rendering of a widget using widgets.py but similarly seem unable to rid myself of the defualt settings - principally based on this thread.
Any ideas or solution to rid myself of the checkbox would be gratefully received!

I think this is to do with the inlineformset_factory applying a default can_delete parameter set to true, which was present regardless of how I'd prepared the form to use with it. Simply passing can_delete=False got rid of the Delete checkbox.
SpecImageFormSet = inlineformset_factory(Spec, SpecImage, form=SpecImageForm, extra=1, max_num=1, can_delete=False)
In addition when I rendered the form on it's own (without using inlineformset_factory) there was no sign of a 'Delete checkbox'. Then I found this SO post that explained why.
Getting there.

Related

customise django widget in template

I have standard model form in django with Imagefield and standard widget. It made me such output on the page:
Currently: qwe/Tulips.jpg <input id="image-clear_id" name="image-clear" type="checkbox" /> <label for="image-clear_id">Clear</label><br />
Change: <input id="id_image" name="image" type="file" />
I want to place outputs of this widget in different parts of page. How can I cut it in templates.
If there is a way to use part of the output in template like {{form.name_of_field.label}} or {{form.name_of_field.errors}}
I've tried different names but no use
There must be a way to use them apart.
And yet another one who needs form styling.
I would recommend to use Widget Tweaks
<form method='POST' action="/" enctype='multipart/form-data'>
{% load widget_tweaks %}
{% csrf_token %}
{{ form.first_name |add_class:"customCSS1 customCSS2" }}
{{ form.second_name |add_class:"customCSS3 customCSS4" }}
</form>
{{ form.media.js }}
with this plugin you can style the form as you wish. All Css classes work. You can put each form field wherever you want on the Page. Is that what you are looking for? Your question is a bit misleading.
Hope that helps if not leave a comment :)

Bootstrap for Django form: break down the fields of the form to 3 pages

I have a Django form, which has a lot of fields so that I have to break it up to 3 pages. It means user has to fill some fields of the form in one page , and then they click next to go to next pages and continue to fill the forms.
To achieve that, I plan to display some fields of the form on each page.
I have come up with this code:
HTML Page 1:
<form method="POST" action="#" class="form">
{{form.email}}
{{form.phone_number}} ...
</form>
HTML Page 2 :
<form method="POST" action="#" class="form">
{{form.current_job}}
{{form.current_salary}}...
</form>
It works fine with this code but it just shows the form in basic appearance, I would like to use bootstrap to make it more beautiful.
My questions is that, how can I integrate bootstrap ?
I have come up with this solution, but it is hard-coded and difficult if I changes fields of the form in the future:
<label class="control-label" for="id_field1">Field 1</label>
<input class="form-control" id="id_field1" maxlength="50" name="field1" type="text"/>
<label class="control-label" for="id_field2">Field 2</label>
<input class="form-control" id="id_field2" maxlength="50" name="field2" type="text"/>
Thank you for your help!

BooleanField checkbox not render correctly with crispy_forms using bootstrap

I am using crispy_forms and FormHelper. I have a model field declared as:
active = models.BooleanField(default=True)
And in my ModelForm, I have tried both the following in my Layout:
self.helper.layout = Layout(
...
InlineCheckboxes('active'),
Field('active'),
...
which both not providing the desired result:
Please see image link
While using InlineCheckboxes, I do not see the checkbox and using only Field, it's not formatted correctly.
Please help
Here is the link to the "Bootstrap Layout objects" section of Crispy Forms docs.
InlineCheckboxes: It renders a Django forms.MultipleChoiceField field using inline checkboxes
InlineCheckboxes isn't appropriate for your model's field-type.
A hacky way to achieve what you're looking for is to use PrependedText with an empty string for the text argument.
...
PrependedText('active', ''),
...
Examining the source it appears that a boolean field by default renders the <input> tag inside the <label> tag. Using the hack above, 'Active' stays in the <label> and the <input> is put where you'd expect: in a <div> with "control" css class. Compare the following:
PrependedText('active', ''):
<div id="div_id_active" class="form-group">
<label for="id_active" class="control-label">Active</label>
<div class="controls">
<div class="input-group">
<input type="checkbox" name="active" class="checkboxinput" id="id_active" />
</div>
</div>
</div>
Field('active'):
<div class="form-group">
<div id="div_id_active" class="checkbox">
<div class="controls">
<label for="id_active" class=""><input type="checkbox" name="active" class=
"checkboxinput checkbox" id="id_active" /> Active</label>
</div>
</div>
</div>
Update
I've confirmed that this is fixed in the dev branch of django-crispy-forms.
Reference this commit: 5c3a268
And this github issue: #267

How to add custom attribute to html (form) from models form?

This is standard checkbox from model forms:
In my HTML I have: {{form}}
In website source:
<div class="id_accept-control-group control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="accept" id="id_accept" /> <span>Accept</span>
</label>
</div>
</div>
How to add custom attribute: disabled="disabled" checked="checked" (to input)?
Check out this question to point you in the right direction Django: How do I add arbitrary html attributes to input fields on a form?
Also take a look at the model forms django doc https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

Customizing Django forms with RadioSelect widget

So I'm using jQuery UI to skin the radio buttons but I can't get Django to render my form the way it has to be done.
I need to have this structure:
<table>
<tr>
<td><label for="notify_new_friends">Notify when new friends join</label></td>
<td class="radio">
<input type="radio" name="notify_new_friends" id="notify_new_friends_immediately" value="1" checked="checked"/><label for="notify_new_friends_immediately">Immediately</label>
<input type="radio" name="notify_new_friends" id="notify_new_friends_never" value="0"/><label for="notify_new_friends_never">Never</label>
</td>
</tr>
</table>
So to summarize that I need the radio buttons within a class (radio) where they have an input and a label for.
When I render the form in my template with {{ profile_form.notify_new_friends }} I get the following:
<ul>
<li><label for="id_notify_new_friends_0"><input type="radio" id="id_notify_new_friends_0" value="0" name="notify_new_friends" /> Immediately</label></li>
<li><label for="id_notify_new_friends_1"><input type="radio" id="id_notify_new_friends_1" value="1" name="notify_new_friends" /> Never</label></li>
</ul>
Which is exactly what I want except for the list-part. So I tried looping over it which gives me the labels formatted differently:
{% for item in profile_form.notify_new_friends %}
{{ item }}
{% endfor %}
which gives me:
<label><input type="radio" name="notify_new_friends" value="0" /> Immediately</label>
<label><input type="radio" name="notify_new_friends" value="1" /> Never</label>
So the problem here is that it stops using label for and starts using just label to wrapp it all with.
I also tried doing something like this, but then the label and label_tag don't render anything.
{{ profile_form.notify_new_friends.0 }}
{{ profile_form.notify_new_friends.0.label_tag }}
{{ profile_form.notify_new_friends.0.label }}
So does anyone know how I can render this properly!?
FYI, this is my forms.py:
self.fields['notify_new_friends'] = forms.ChoiceField(label='Notify when new friends join', widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
In my code I discovered that changing the widget from
forms.RadioSelect
to
forms.RadioSelect(attrs={'id': 'value'})
magically causes the resulting tag value to include the id attribute with the index of the item appended. If you use
{% for radio in form.foo %}
<li>
{{ radio }}
</li>
{% endfor %}
in the form you get a label wrapped around an input. If you want the more conventional input followed by label, you need to do this:
{% for radio in form.value %}
<li>
{{ radio.tag }}
<label for="value_{{ forloop.counter0 }}">{{ radio.choice_label }}</label>
</li>
{% endfor %}
Unfortunately this is more complicated than it should be, it seems you need to override at least 2 classes: RadioRenderer and RadioInput. The following should help you get started but you might need to tweak it a little.
First create a custom radio button input widget. The only purpose of us overriding the render method is to get rid of annoying structure Django enforces (<label><input /></label>) where instead we want ours (<label /><input />):
class CustomRadioInput(RadioInput):
def render(self, name=None, value=None, attrs=None, choices=()):
name = name or self.name
value = value or self.value
attrs = attrs or self.attrs
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'%s<label%s>%s</label>' % (self.tag(), label_for, choice_label))
Now we need to override RadioRenderer in order to:
Force it to use our custom radio input widget
Remove <li> wraping every single input field and <ul> wrapping all input fields:
Something along these lines should do:
class RadioCustomRenderer(RadioFieldRenderer):
def __iter__(self):
for i, choice in enumerate(self.choices):
yield CustomRadioInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx]
return CustomRadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
def render(self):
return mark_safe(u'%s' % u'\n'.join([u'%s' % force_unicode(w) for w in self]))
Finally instruct Django to use custom renderer
notify_new_friends = forms.ChoiceField(label='Notify when new friends join', widget=forms.RadioSelect(renderer=RadioCustomRenderer), choices=NOTIFICATION_CHOICES)
Please bear in mind: This now outputs radio buttons together with encompassing <td> hence you need to build a table around it in your template, something along these lines:
<table>
<tr>
<td><label for="{{field.auto_id}}">{{field.label}}</label></td>
<td>{{ field.errors }} {{field}}</td>
</tr>
</table>
If anyone stumble upon this problem and just want to render the radio button without ul: they should follow this link.
https://docs.djangoproject.com/en/3.1/ref/forms/widgets/#selector-widgets
Example below.
{% for radio in myform.beatles %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
Since it doesn't seem to be a good way to do this I chose to rearrange the generated code using jQuery.
// First remove the ul and li tags
$('.radio ul').contents().unwrap();
$('.radio li').contents().unwrap();
// Then move the input to outside of the label
$('.radio > label > input').each(function() {
$(this).parent().before(this);
});
// Then apply the jQuery UI buttonset
$( ".radio" ).buttonset();
This made it go from:
<ul>
<li><label for="id_notify_new_friends_0"><input type="radio" id="id_notify_new_friends_0" value="0" name="notify_new_friends" /> Immediately</label></li>
<li><label for="id_notify_new_friends_1"><input type="radio" id="id_notify_new_friends_1" value="1" name="notify_new_friends" /> Never</label></li>
</ul>
to:
<input type="radio" id="id_notify_new_friends_0" value="0" name="notify_new_friends" /><label for="id_notify_new_friends_0"> Immediately</label></li>
<input type="radio" id="id_notify_new_friends_1" value="1" name="notify_new_friends" /><label for="id_notify_new_friends_1"> Never</label></li>
and my jQuery UI styling works fine.
Try like this , I got it..
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
class RadioCustomRenderer( RadioFieldRenderer ):
def render( self ):
return mark_safe(u'%s' % u'\n'.join([u'%s' % force_unicode(w) for w in self]))
in form
widgets = {
'validity': forms.RadioSelect(renderer=RadioCustomRenderer),
}