I am using django crispy_forms.helper and crispy_forms.layout to create radio button with options. The label and radio button options are overlapping.
The code which i am using is :
forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, HTML, Layout, Row, Div, Fieldset,ButtonHolder,Column
from crispy_forms.bootstrap import InlineRadios, PrependedAppendedText, Div
ROUTER_OPTIONS = (
('', 'Choose router...'),
('FIP', 'First IP in range'),
('AM', 'Add Manually')
)
class DhcpForm(forms.ModelForm):
router = forms.ChoiceField(label='Router',
choices=ROUTER_OPTIONS,
initial='', widget=forms.RadioSelect)
def __init__(self, *args, **kwargs):
super(DhcpForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout(
Row(
Column('dhcp_member', css_class='form-group col-md-6 mb-0'),
Column('router', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
)
html
{% block content %}
{% crispy form %}
{% endblock %}
The view which i am getting:
overlapped view
In your Choice field Add the style function and set the display as flex given below.
Column('router', css_class='form-group col-md-6 mb-0', style='display: flex')
Related
I am using Crispy Forms and layout helper to generate my Input form. I'd like to add a Toggle switch into the form.
desired result:
what I get:
forms.py:
class RequestForm(forms.ModelForm):
on_prem = forms.CharField(widget=forms.CheckboxInput(attrs={"class": "slider form-control"}))
class Meta:
model = Request
fields = ['on_prem']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Div(
Div(Field('on_prem'), css_class='col-md-3', ),
css_class='row',
),
)
models.py:
class Request(models.Model):
on_prem = models.BooleanField(default=False)
form.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% crispy form %}
<button type="submit" class="d-block btn mt-4 w-50 mx-auto">
Save Request
</button>
</form>
I have seen in the Bootstrap documentation that the toggle switch effect I desire is achieved with nested css classes and I am not sure how to achieve that via the form helper. Any help would be greatly appreciated.
Fewer lines of code just using "Field":
self.helper.layout = Layout(
Field('notify_faculty_field', css_class="form-check-input", wrapper_class="form-check form-switch"),
)
I managed to achieve this by using HTML blocks in the helper.
form.py
class RequestForm(forms.ModelForm):
on_prem = forms.CharField(widget=forms.CheckboxInput(attrs={"class": "slider form-control"}))
class Meta:
model = Request
fields = ['on_prem']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Div(
Div(
HTML('<label class="form-check-label" for="on_prem">On Prem</label>'),
HTML('<div class="form-switch">'),
Field('on_prem'),
HTML('</div>'),css_class='col-md-3',),
css_class='row',
),
)
When the page loads I am seeing the error of - "This field is required" with the input form 'Title' highlighted with the red board. I would expect that this should only show after the Save button is pressed. I can toggle the message on and off with self.helper.form_tag but the behavior seems incorrect to me, it seems as though it is trying to submit before I click save.
Am I doing something wrong or is this expected behavior? If it is expected is there a way to change it to only show the warnings after Save?
forms.py
from django import forms
from .models import Request, RequestDocument
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, Div, Layout
class RequestForm(forms.Form):
title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'title'}))
rfp_No = forms.CharField(widget=forms.TextInput(attrs={}), required=False)
company_Name = forms.CharField(widget=forms.TextInput(attrs={}), required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
#self.helper.form_tag = False
self.helper.help_text_inline = True
self.helper.layout = Layout(
Div(Field('title'), css_class='col-md-12', ),
Div(
Div(Field('rfp_No'), css_class='col-md-6', ),
Div(Field('company_Name'), css_class='col-md-6', ),
css_class='row',
),
)
create.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<form method="post">
{% csrf_token %}
{% crispy form %}
<button type="submit" class=" d-block btn btn-lg btn-success mt-4 w-50 mx-auto">
Save
</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$(".active").removeClass("active");
$("#link-create").addClass("active");
});
</script>
adding self.helper.form_show_errors = False to the init hides the errors but this the block actual errors from showing such as if the max length was exceeded.
I eventually figured this out by splitting the POST and GET methods in my form.
forms.py
form = RequestForm()
if request.method == 'POST':
##Do Post Stuff
elif request.method == 'GET':
##Do Get Stuff
else:
context = {
}
return render(request, "requests/create.html", context)
I've searched through Stackoverflow for this and cannot find an answer.
I am trying to render a ModelForm using crispy forms and FormHelper to help me lay it out nicely.
Everything was working fine when I was using the forms.Form library. but the main problem now is that the date picker and the choices field no longer have a dropdown list with the datepicker or the
So this is my forms.py file:
CITIES= (("London","London"), ("Istanbul","Istanbul"), ("Cape Town","Cape Town"))
class EntryForm(forms.ModelForm):
class Meta:
model = Items
itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
...
date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
location =forms.ChoiceField(choices=CITIES, required=False)
fields = ['itemName', 'date', 'location']
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'itemName',
...
Row(
Column('date', css_class='form-group col-md-6 mb-0'),
Column('location', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Submit('submit','Submit')
)
My template file looks like this:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Entry Form</h1>
<br>
{% crispy form %}
<br>
{% endblock %}
Not 100% certain if this is the issue, but I think you might just need to shift the fields to the EntryForm class, like so:
class EntryForm(forms.ModelForm):
# Fields should go here, not under the Meta class:
itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
...
date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
location =forms.ChoiceField(choices=CITIES, required=False)
class Meta:
model = Items
fields = ['itemName', 'date', 'location']
I've a form named "CarForm". I 've created a "Create Form" to create car record using crispy form. I would like to ask is it possible to display the detail and update the car record using the same form?
Here is the code for CarForm:
from .models import *
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Row, Column
from crispy_forms.bootstrap import PrependedAppendedText, PrependedText, FormActions
from django.urls import reverse
class CarForm(forms.ModelForm):
note = forms.CharField(widget=forms.Textarea())
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['note'].required = False
self.fields['policy_num'].required = False
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_action = reverse('create')
self.helper.layout = Layout(
Row(
Column('reg_num', css_class='form-group col-md-6 mb-0'),
Column('make', css_class='form-group col-md-6 mb-0'),
Column('year', css_class='form-group col-md-4 mb-0'),
Column('color', css_class='form-group col-md-4 mb-0'),
Column('cc', css_class='form-group col-md-4 mb-0'),
Column('engine_num', css_class='form-group col-md-6 mb-0'),
Column('chasis_num', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
'note',
Row(
Column(PrependedAppendedText('price_buy', 'RM','.00'), css_class='form-group col-md-6 mb-0'),
Column(PrependedAppendedText('price_sell','RM','.00'), css_class='form-group col-md-6 mb-0'),
Column('policy_num', css_class='form-group col-md-12 mb-0'),
Column('owner_name', css_class='form-group col-md-4 mb-0'),
Column('owner_ic',css_class='form-group col-md-4 mb-0'),
Column('owner_phone', css_class='form-group col-md-4 mb-0'),
css_class='form-row'
),
FormActions(
Submit('submit', 'Create'),
)
)
class Meta:
model = Car
exclude = ['date']
Code in views.py.
I've added instance in the edit function, but there is an error for all the field this field is required
def edit(request,id):
car = Car.objects.get(id=id)
form = CarForm(request.POST,instance=car)
context = { 'car':car ,'form':form }
return render(request,'cars/edit.html',context)
def update(request,id):
car = Car.objects.get(id=id)
car.reg_num = request.POST['reg_num']
car.make = request.POST['make']
car.color = request.POST['color']
car.year = request.POST['year']
car.engine_num = request.POST['engine_num']
car.chasis_num = request.POST['chasis_num']
car.note = request.POST['note']
car.price_buy = request.POST['price_buy']
car.price_sell = request.POST['price_sell']
car.policy_num = request.POST['policy_num']
car.owner_name = request.POST['owner_name']
car.owner_ic = request.POST['owner_ic']
car.owner_phone = request.POST['owner_phone']
car.save()
messages.success(request,'Car "%s" updated successfully' % car.reg_num)
return redirect('/cars/list/')
Here is the code for edit.html:
{% block title %}Edit Car Record{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<h1 align="center">Edit Car Record</h1>
{% crispy form %}
{% endblock %}
How can I use the crispy form helper to control the layout of the form elements, for the builtin forms, such as is mentioned in THIS post?
i think its late but i hope it helps you:
forms.py
class PasswordResetFormExtra(auth.forms.PasswordResetForm):
def __init__(self, *args, **kw):
super(PasswordResetFormExtra, self).__init__(*args, **kw)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
'email',
Div(
Submit('submit', 'Reset password', css_class='btn btn-default'),
HTML('<a class="btn btn-default" href="/">Cancel</a>'),
css_class='text-left',
)
)
urls.py
from django.contrib.auth.views import password_reset
from .forms import(
PasswordResetFormExtra,
)
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {
'template_name': 'my_templates/password_reset.html',
'password_reset_form':PasswordResetFormExtra,
}),
)
password_reset.html
{% load crispy_forms_tags %}
{% block content %}
{% crispy form %}
{% endblock %}