I'm using Django 1.7 with bootstrap 3 and want to render each form field the same way, best utilizing bootstrap has-error fields:
<div class="form-group {% if form.field.errors %}has-error has-feedback{% endif %}">
<label class="control-label" for="field">{{ form.field.help_text }}</label>
<div class="input-group">
<span class="input-group-addon"><span class="some-icon"></span></span>
{% render_field form.field class+="form-control" placeholder=form.field.label id="end-date" aria-describedby="inputError2Status" %}
</div>
<label class="control-label" for="field">{{ form.field.errors.as_text }}</label>
</div>
As you can see, the moment the number of fields increase it becomes a LOT of work, not only to write it, but also to maintain it and refactoring becomes a hell... not really DRY. For each field I need to change the form.field variables and id="field" and the icon
How would I write a function, templatetag or something else to make django render all the fields in my form this way? Is it even possible to do this? It would be awesome if the Form in django would have a setting to accept an optionalglypycon class which the renderer will use to render the icon.
-- EDIT --
As indicated by #Serafeim django-crispy-forms could be the solution. But how do I use crispy-forms to produce the above html?
-- EDIT 2 --
After reading up on crispy-forms I managed to come up with the following solution:
My forms.py file looks like this:
class CreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = 'submit'
self.helper.add_input(Submit('submit', 'Submit'))
self.helper.html5_required = True
self.helper.layout = Layout(
PrependedText('fieldA', '<span class="fa fa-calendar"></span>', placeholder="yyyy-mm-dd"),
PrependedText('fieldB', '<span class="fa fa-clock-o"></span>', placeholder="0:00:00 (h:m:s)"),
'fieldC')
fieldA = forms.DateField(required=True)
fieldB = FDurationField(required=True)
fieldC = forms.CharField(widget=forms.Textarea(attrs={'rows':3}), required=False, max_length=128)
class Meta:
model = AModel
exclude = ('fieldD', 'FieldE', 'fieldF', 'fieldG')
and in my template I only have to call {% crispy form %} which is much better than my initial version. However, I still feel like I have to repeat certain steps, like adding the fields to the Layout... Is it possible to reduce the code even further?
It would be awesome if the Form in django would have a setting to
accept an optional glypycon class which the renderer will use to render
the icon.
Forms are just a collection of fields. A Field is a combination of a widget (which control the HTML rendered) and validation rules.
To control what is rendered on the page, you'd modify the widget.
For example, if I want to specify a css class or a placeholder, I would do this at the widget level:
email = forms.EmailField(label='Email Address',
required=False,
widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'user#example.com'}))
You can create your own custom widgets and fields and obtain fine control over how forms are rendered; so what you are asking is absolutely possible; but as this is something that is often repeated, django-crispy-forms has become the defacto standard way of getting this done.
Related
I tried multiple solutions around but couldn't make my select field work in Django Template. I am beginner and humbly apologize if my question is not up to standard. My select button is not showing any options in django form. I only have two options to show. Is there anyway I can get form field without having iterate through it in template? Using Django 3 and Python 3.8. Help will be much appreciated.
Model:
class User(AbstracUser):
ACC_TYPE = (('Student', 'Student'), ('Teacher', 'Teacher'))
role = models.CharField(max_length=100, choices=ACC_TYPE
.....
Form:
class UserForm(UserCreationForm): #Using django's default form
account_type = forms.CharField(widget=forms.Select(choices=User.ACC_TYPE))
model = User
fields =('.............,
'account_type')
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
self.fields['account_type'].choices = [(each[0], each[1]) for each in User.ACC_TYPE]
self.fields['account_type'].required = True
Template:
.......
<select>
{% for opt, val in form.account_type.choices %}
<option value="{{ opt }}">{{ value }}</option>
{% endfor %}
</select>
......
Your logic is fine. You shouldn't be having this issue. Only reason could be and its a long shot...that you are using some bootstrap theme with customized CSS classes in it. Now either you load those custom classes per field or you can use django-crispy-fields that inherits all classes with form-group. You will need to load the form with {{ form|crispy }}. For details please check settings for django-crispy-forms. Remember to load the tag at top of page where you want to use it as per settings {% load crispy_forms_tags %}. Read Docs here.
So I am trying to change my form's model Datefield output to the Datepicker similar to DatepickerWidget in CreateView
The forms are generated using a html template:
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.error }}</span>
</div>
<label class="control-label col-sm-2">{{field.label_tag}}</label>
<div class="col-sm-10">{{field}}</div>
</div>
{% endfor %}
Here is the Views with what I tried:
class newenv_form(generic.CreateView):
model = Environment
fields =['name', 'description', 'creation_date', 'status','status_update_date']
template_name = 'catalogue/new_env.html'
#Does not work
def get_form(self, form):
form = super(newenv_form, self)
form.fields['creation_date','status_update_date'].widget = forms.DateInput(attrs={'class':'datepicker'})
return form
Here is what worked but it is a dropdown datepicker that is limited in choices
def get_form(self):
'''add date picker in forms'''
from django.forms.extras.widgets import SelectDateWidget
form = super(EnvironmentCreateView, self).get_form()
form.fields['creation_date'].widget = SelectDateWidget()
return form
Note that I remove form_class which was causing problems
UPDATE: On Django 3.1, you can find SelectDateWidget within django.forms.widgets
Try to change the following line in the method get_form:
form = super(newenv_form, self)
to:
form = super(newenv_form, self).get_form(form)
And please follow the conventions and use PascalCase for class names in python.
You could call this class EnvironmentCreateView. Further generic view classes could be called for example EnvironmentListView, EnvironmentDetailView, EnvironmentUpdateView, EnvironmentDeleteView.
Using the same pattern for all your model classes will produce comprehensible code.
EDIT (2017-10-24):
Regarding your comment here is a further explanation. Although it is hard to give a correct remote diagnosis, I'd suggest the following changes:
class EnvironmentCreateView(generic.CreateView):
# class attributes ...
def get_form(self, form_class=None):
form = super(EnvironmentCreateView, self).get_form(form_class)
# further code ...
The essential changes are in bold. The class name is changed to meet the conventions. Also the parameter form is changed to form_class to meet the convetions, too. I emphasise conventions in particular, because it makes the code very comprehensible to other people familiar with the framework.
The important change is that form_class has the initial value None.
That should solve the problem with the error.
In the body of the method you call the parent method with super and write after that your custom code.
Please check the documentation for generic.CreateView. It inherits, among others, from generic.FormMixin. That is the class with the method get_form.
In Django, one applies CSS styling to class-based form fields in forms.py (or equivalent).
My question: is it impossible to do it any other way inside a Django project?
I'll accept the answer even if the answer is "it's impossible". Hacks and tricks are acceptable as well. Illustrative examples would be great.
p.s. here's an example of a Django form where I've styled in the class-based form:
class SampleForm(forms.Form):
description = forms.CharField(max_length=250)
def __init__(self,*args,**kwargs):
super(SampleForm, self).__init__(*args,**kwargs)
self.fields['description'].widget.attrs['class'] = 'btn bcg'
self.fields['description'].widget.attrs['style'] = 'background-color:#F8F8F8; width:98%; color: #1f8cad;'
self.fields['description'].widget.attrs['autocomplete'] = 'off'
You can use template tags.
css.py
from django import template
register = template.Library()
#register.filter(name='css')
def css(field, css):
return field.as_widget(attrs={"style":css})
in your template:
{% load css %}
{{ item.field|css: 'width: 100px' }}
the result could be
<input id="id_field" name="field" style="width: 100px" type="text" />
As you can see, in style is your variable (width: 100px). You can also do it with class.
I am new to django forms and Crispy Forms. I have some simple forms in a little forum Im developing. I think I don't need to use the %crispy% tag. I only need the form|crispy filter. However, I don't know why they don't render the error messages.
Also, if I want to customize the error messages (they must be in spanish), do I need to use the %crispy% tag or is it possible to do this with the |crispy filter?
Anyway, here is one of my forms:
from django import forms
from django.forms import Textarea
class FormNuevoVideo(forms.Form):
url = forms.URLField(initial='http://', max_length=250)
titulo = forms.CharField(max_length=150)
descripcion = forms.CharField(
help_text="...",
widget=Textarea(attrs={'rows': 3, 'data-maxlength': 500}))
Here is the view:
#login_required
def nuevo_video(request, slug):
template = 'videos/nuevo.html'
tema = Temas.objects.get(slug=slug)
if request.method == 'POST':
form = FormNuevoVideo(request.POST)
if form.is_valid():
...
nuevo_video.save()
return redirect('videos:videos_tema', slug=tema.slug, queryset='recientes')
else:
return redirect('videos:nuevo_video', slug=tema.slug) #this same view.
else:
form_nuevo_video = FormNuevoVideo()
context = {'form_nuevo_video': form_nuevo_video, 'tema': tema}
return render(request, template, context)
And in the HTML:
{% block form %}
<form action = "{% url 'videos:nuevo_video' tema.slug %}" method = "post">
{% csrf_token %}
{{form_nuevo_video|crispy}}
<input class = "btn pull-right" type = "submit" value ="enviar"/>
</form>
{% endblock form %}
So, lets say, when someone tries to submit a video with a title of more than 150 characters, it doesn't display the error. I am sure I am missing something simple. Also, I'd like to customize the error messages so that they are in spanish. Thanks in advance.
I know you can specify fieldsets in django for Admin helpers. However, I cannot find anything useful for ModelForms. Just some patches which I cannot use. Am I missing something? Is there a way I could achieve something like fieldsets without manually writing out each field on my template in the appropriate tag.
I would ideally like to iterate through a set of BoundFields. However, doing something like this at the end of my ModelForm:
fieldsets = []
fieldsets.append(('Personal Information',
[username,password,password2,first_name,last_name,email]),) # add a 2 element tuple of string and list of fields
fieldsets.append(('Terms & Conditions',
[acceptterms,acceptprivacy]),) # add a 2 element tuple of string and list of fields
fails as the items contained in my data structure are the raw fields, not the BoundFields. t looks like BoundFields are generated on the fly... this makes me sad. Could I create my own subclass of forms.Form which contains a concept of fieldsets (even a rough one that is not backward compatible... this is just for my own project) and if so, can you give any pointer? I do not want to mess with the django code.
I think this snippet does exactly what you want. It gives you a Form subclass that allows you to declaratively subdivide your form into fieldsets and iterate through them in your template.
Update: that snippet has since become part of django-form-utils
Fieldsets in modelforms are still in "design" stage. There's a ticket in Django trac with low activity.
It's something I've been interested in researching myself in the near future, but since I haven't done it yet the best I can offer are these snippets:
Form splitting/Fieldset templatetag
Sectioned Form
Forms splitted in fieldsets
Edit: I just noticed this question again and I realize it needs an edit to point out Carl's project django-form-utils which contains a BetterForm class which can contain fieldsets. If you like this project give him a +1 for his answer below :)
One thing you can do is break your logical fieldsets into separate model form classes.
class PersonalInfoForm (forms.ModelForm):
class Meta:
model=MyModel
fields=('field1', 'field2', ...)
class TermsForm (forms.ModelForm):
class Meta:
model=MyModel
fields=('fieldX', 'fieldY', ...)
Pass them to your template in different variables and break up the formsets:
<form ...>
<fieldset><legend>Personal Information</legend>
{{ personal_info_form }}
</fieldset>
<fieldset><legend>Terms and Conditions</legend>
{{ terms_form }}
</fieldset>
</form>
In that sense each of your form classes is just a fragment of the actual HTML form.
It introduces a touch of complexity when you call save on the form. You'll probably want to pass commit=False and then merge the resultant objects. Or just avoid using ModelForm.save altogether and populate your model object by hand with 'cleaned_data'
Daniel Greenfelds django-uni-form solves this with a the Layout helper class. I'm trying it out right now and it looks pretty clean to me.
Uniform helpers can use layout objects. A layout can consist of fieldsets, rows, columns, HTML and fields.
I originally picked Django-uni-form because it complies with section 508.
You can use this package: https://pypi.org/project/django-forms-fieldset/
pip install django-forms-fieldset
Add forms_fieldset to your INSTALLED_APPS setting like this:
INSTALLED_APPS = [
...
'forms_fieldset',
]
Add fieldsets in your form
from django.forms import ModelForm
from .models import Student
class StudentForm(ModelForm):
fieldsets = [
("Student Information", {'fields': [
('first_name', 'last_name'),
('email', 'adress'),
]}),
("Parent Information", {'fields': [
'mother_name',
'father_name',
]}),
]
class Meta:
model = Student
fields = '__all__'
In your views
def home(request):
form = StudentForm()
if request.method == 'POST':
form = Form(request.POST, request.FILES)
#save...
context = {
'form': form,
}
return render(request, 'home.html', context)
in your template
{% load forms_fieldset static %}
<link rel="stylesheet" type="text/css" href="{% static 'forms_fieldset/css/main.css' %}">
<form>
{{ form|fieldset:'#42945c' }}
</form>
This was the code that I developed in order to understand custom tags (with links). I applied it to create a fieldset.
Disclaimer: I encourage the use of any of the above answers, this was just for the sake of learning.
templatetags/myextras.py:
from django import template
from django.template import Context
register = template.Library()
class FieldsetNode(template.Node):
""" Fieldset renderer for 'fieldset' tag """
def __init__(self, nodelist, fieldset_name):
""" Initialize renderer class
https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-the-renderer
:param nodelist: a list of the template nodes inside a block of 'fieldset'
:param fieldset_name: the name of the fieldset
:return: None
"""
self.nodelist = nodelist
self.fieldset_name = fieldset_name
def render(self, context):
""" Render the inside of a fieldset block based on template file
https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#auto-escaping-considerations
:param context: the previous template context
:return: HTML string
"""
t = context.template.engine.get_template('myapp/fieldset.html')
return t.render(Context({
'var': self.nodelist.render(context),
'name': self.fieldset_name,
}, autoescape=context.autoescape))
#register.tag
def fieldset(parser, token):
""" Compilation function for fieldset block tag
Render a form fieldset
https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-the-compilation-function
https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#parsing-until-another-block-tag
:param parser: template parser
:param token: tag name and variables
:return: HTML string
"""
try:
tag_name, fieldset_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0])
if not (fieldset_name[0] == fieldset_name[-1] and fieldset_name[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's argument should be in quotes" % tag_name)
nodelist = parser.parse(('endfieldset',))
parser.delete_first_token()
return FieldsetNode(nodelist, fieldset_name[1:-1])
templates/myapp/fieldset.html:
<div class="fieldset panel panel-default">
<div class="panel-heading">{{ name }}</div>
<div class="panel-body">{{ var }}</div>
</div>
templates/myapp/myform.html:
<form action="{% url 'myapp:myurl' %}" method="post">
{% csrf_token %}
{% fieldset 'General' %}
{{form.myfield1 }}
{% endfieldset %}
{# my submit button #}
</form>