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 :)
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!
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
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/
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),
}