My form is here:
class SortFieldsForm(forms.Form):
LatestyearModel=forms.BooleanField(label="latest year")
LowestPrice=forms.BooleanField(label="lowest price")
HighestPrice=forms.BooleanField(label="highest price")
Newest_Entry=forms.BooleanField(label="latest date")
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_id = 'id-exampleForm'
self.helper.form_class = 'form-inline'
self.helper.form_method = 'post'
self.helper.form_action = 'sort_posting'
#self.helper.add_input(Submit('submit', 'Submit'))
super(SortFieldsForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
#Fieldset(
# 'price',
# 'LowestPrice',
# 'HighestPrice',
),
PrependedText('LowestPrice', ''),
PrependedText('HighestPrice', ''),
PrependedText('Newest_Entry', ''),
PrependedText('LatestyearModel', ''),
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
Currently the form shows as this:
I want to group lowest price and highest price in one radioselect,
latest date and latest year as checkboxes neatly aligned with submit button next to the field. Not below them as it currently now.
Any pointers/tips?
Try this out:
class SortFieldsForm(forms.Form):
LatestyearModel=forms.BooleanField(label="latest year")
LowestPrice=forms.BooleanField(label="lowest price")
HighestPrice=forms.BooleanField(label="highest price")
Newest_Entry=forms.BooleanField(label="latest date")
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_id = 'id-exampleForm'
self.helper.form_class = 'form-inline'
self.helper.form_method = 'post'
self.helper.form_action = 'sort_posting'
#self.helper.add_input(Submit('submit', 'Submit'))
super(SortFieldsForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
'LowestPrice',
'HighestPrice',
'Newest_Entry',
'LatestyearModel' ,
ButtonHolder(
Submit('submit', 'Submit', css_class='button white')
)
)
You should use ChoiceField and MultipleChoiceField with labels and custom widgets RadioSelect and CheckboxSelectMultiple.
More explanation
First, some code. I said about CheckboxSelectMultiple but you can do without it. RadioSelect is actually needed for radio buttons. You can place checkboxes and radio buttons after their labels using Bootstrap horizontal form layout.
class SortFieldsForm(forms.Form):
price_order=forms.ChoiceField(widget=forms.RadioSelect, choices=(('lowest', 'Lowest first'), ('highest', 'Highest first')))
newest_entry=forms.BooleanField(label="Latest date")
latest_year=forms.BooleanField(label="Latest year")
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-8'
helper.layout = Layout(
'price_order',
'newest_entry',
'latest_year',
Submit('submit', 'Submit', css_class='button white'))
Try to do like this. I cannot guarantee if there is no typos but you can achieve your goals this way.
Also, check out links below:
https://docs.djangoproject.com/en/dev/ref/forms/widgets/
http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html#bootstrap3-horizontal-forms
Learn about bootstrap and its classes.
Related
The technical issue of styling buttons in django crispy forms. I would like to apply my own class, without using the primary button class.
class MyForm(Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fields("field_1"),
Fields("field_2"),
Submit('submit', u'On', css_class='own-css-class'),
)
Basically, I solved this by adding self.helper.form_tag = False and inserting the button code directly into the html template. In addition, I deleted the submit button from the layout.
class MyForm(Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fields("field_1"),
Fields("field_2"),
)
self.helper.form_tag = False
Is this solution correct and will it be compatible in the long term?
I'd recommend that you create your own custom button and use that when creating your layout.
class CustomButton(BaseInput)
input_type = 'submit'
field_classes = 'my custom css'
class RatingForm(forms.Form):
def __init__(self, *args, lista_de_productores, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
for p in lista_de_productores:
CHOICES = (('1', '1',), ('2', '2',), ('3', '3',) , ('4', '4',) , ('5', '5',))
self.fields[str(p)] = forms.ChoiceField(required=True, widget=forms.RadioSelect(), choices=CHOICES)
helper = FormHelper()
helper.layout = Layout(
InlineRadios(str(p))
)
Not sure what I'm doing wrong but this just displays normal radio buttons instead of inline
Looks like a simple oversight: in your __init__ method, you need to set the self.helper property, rather than creating a variable named helper. This should work for you:
class RatingForm(forms.Form):
def __init__(self, *args, lista_de_productores, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
for p in lista_de_productores:
CHOICES = (('1', '1',), ('2', '2',), ('3', '3',) , ('4', '4',) , ('5', '5',))
self.fields[str(p)] = forms.ChoiceField(required=True, widget=forms.RadioSelect, choices=CHOICES)
# set the self.helper property:
self.helper = FormHelper()
self.helper.layout = Layout(
InlineRadios(str(p))
)
I have a manytomany object in a model form which I want to be rendered as select fields under each other, but whatever I try, i keep getting them next to each other with crispy django forms
class ContactForm(forms.ModelForm):
choice = forms.ModelMultipleChoiceField(label=_('Request'), widget=forms.CheckboxSelectMultiple(),required=False,
queryset=ContactFormChoices.objects.all())
name = forms.CharField(label=_('Name'))
email = forms.EmailField(required=False, label=_('E-mail'))
phone_number = forms.CharField(required=False, label=_('Phone number'))
message = forms.CharField( widget=forms.Textarea , label=_('Message'))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Field('name', css_class='input-xlarge'),
Field('email', css_class='input-xlarge'),
Field('phone_number', css_class='input-xlarge'),
Field('message', rows="3", css_class='input-xlarge'),
#'choice',
Field('choice'),
FormActions(
Submit('submit', _('Submit'), css_class="btn-primary")
)
)
class Meta:
model = ContactData
fields = ['name','message','email','phone_number','choice']
and the model:
class ContactFormChoices(models.Model):
'''
The contact form options to show
'''
text = models.CharField(max_length=256)
active = models.BooleanField(default=True)
def __unicode__(self):
return self.text
class ContactData(models.Model):
'''
The contact data (when customer fills in the contact form,
this is mailed and saved here
'''
name = models.CharField(max_length=256,help_text=_("Name"))
phone_number= models.CharField(max_length=256,null=True,blank=True,default=None)
email = models.EmailField(max_length=256,null=True,blank=True,default=None)
choice = models.ManyToManyField(ContactFormChoices,blank=True,default=None)
message = models.TextField()
def __unicode__(self):
return self.name
it looks like this:
Anybody any suggestion?
wow, after searching and trying a lot.... the answer seem to be very simple:
helper.layout = Layout(
Field('name', css_class='input-xlarge'),
Field('email', css_class='input-xlarge'),
Field('phone_number', css_class='input-xlarge'),
Field('message', rows="3", css_class='input-xlarge'),
PrependedText('choice', ''),
FormActions(
Submit('submit', _('Submit'), css_class="btn-primary")
)
)
and partly duplicate to this question and answer: BooleanField checkbox not render correctly with crispy_forms using bootstrap
I have a one field form which I want to align horizontally and centre of page.
I want to have autofocus and placeholder enabled.
Here is my code:
class VinForm(forms.Form):
VIN = forms.CharField(max_length=17, label='VIN')
def __init__(self, *args, **kwargs):
super(VinForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
#self.helper.form_class = 'form-horizontal col-xs-12 col-md-6 col-lg-5'
self.helper.form_class = 'form-horizontal'
#self.helper.form_class = 'form-inline col-md-12'
#self.helper.label_class = 'col-xs-3 col-md-3 col-lg-3'
#self.helper.field_class = 'col-xs-12 col-md-12 col-lg-12'
#self.helper.form_class = 'form-inline'
self. helper.layout = Layout(
FieldWithButtons('VIN', StrictButton("Go!"), autofocus=True, placeholder='JN1HJ01F8RT231164'),
# Div(
# Div('VIN',css_class='col-md-6',autofocus=True, placeholder='JN1HJ01F8RT231164'),
# css_class='row',
# ),
# Fieldset(
# #'Get Driving profile',
# Field('VIN', autofocus=True, placeholder='JN1HJ01F8RT231164'),
# ),
# FormActions(
# Submit('submit', 'get vehicle info'),
# ),
# )
)
you can see from my code above that I tried many things still none worked. Here is how it looks.
It lacks
1) center of page
2) inline form
3) autofocus and placeholders are not working
I am using twitter bootstrap3
I do the below. Note 'Field' in the snippet below, where we specify additional css in css_class. Here is the docs link
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Row(
HTML('<h3>About you</h4>'),
Column(Field('computers', css_class='text-center'), css_class='col-md-12 text-center')
),
https://stackoverflow.com/a/24812832/960471
The crispy forms documentation shows how to do horizontal forms for bootstrap, perhaps that will help. http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html?highlight=horizontal#bootstrap3-horizontal-forms
I've got a modelform_formset that I'm rendering with django-crispy. Inside the layout of form used I have the following:
self.helper.layout = Layout(
Field('remove', css_class="inline"),
HTML('{{ form.instance.user.get_full_name|title }} ({{ form.instance.user }})'),
Field('is_admin')
)
Note the {{form.instance}} - That's not getting rendered properly binding. Is there a way to get the value for the specific model?
I would recommend you do this. This captures the case where you don't have an instance :D
class XYXForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(XYXForm, self).__init__(*args, **kwargs)
label = "New Object"
if self.instance:
label = '{0} {1}'.format(
self.instance.user.get_full_name.capitalize(),
self.instance.user)
self.helper = FormHelper()
self.helper.form_id = 'community_form'
self.helper.form_method = 'post'
self.helper.layout = Layout(
Field('remove', css_class="inline"),
HTML(label),
Field('is_admin')
)
HTH