CSS styling in Django forms
Taken from my answer to:
How to markup form fields with <div class='field_type'> in Django
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))
or
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})
or
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
}
--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented
-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.
How can I style a django form with css?
Within your template you have to just import the css
file in the head tag
, but do ensure you load static
first.
html file:
{% load static %}
<!doctype html>
<html lang="en">
<head>
# import the css file here
<link rel="stylesheet" href="{% static 'path to css file' %}">
</head>
...
</html>
Within the css file:
# Styling the class
.myfieldclass{
width: 30% !important;
height: 100px !important;
...
}
But please note that you don't have to import a css file since you can add the style tag in the head tag as well. For example:
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
.myfieldclass{
width: 30% !important;
height: 100px !important;
...
}
</style>
</head>
...
</html>
You could apply css
from the python
file itself as well.
Approach from the python
file.
# Custom way to set css styling on a form field in python code
def field_style():
styles_string = ' '
# List of what you want to add to style the field
styles_list = [
'width: 30% !important;',
'height: 100px !important;',
]
# Converting the list to a string
styles_string = styles_string.join(styles_list)
# or
# styles_string = ' '.join(styles_list)
return styles_string
class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass', 'style': field_style()}))
# 'style': field_style() .... field_style() will return in this case 'width: 30% !important; height: 100px !important;'
Any of those should work but I do recommend doing the styling from the hmtl
or css
file instead.
Add custom CSS styling to model form django
Try this:
forms.py
class EmailForm(forms.ModelForm):
...
subject = forms.CharField(
label = 'Subject',
max_length = 1000,
required = True,
widget = forms.TextInput(
attrs = {'class': 'summernote', 'name': 'subject'}
)
)
body = forms.CharField(
label = 'Body',
max_length = 1000,
required = True,
widget = forms.TextInput(
attrs = {'class': 'summernote', 'name': 'body'}
)
)
...
class Meta:
model = MarketingEmails
fields = ('messageid','subject','body','name', ... )
view.py
from django.shortcuts import render
from your_app_path.forms import EmailForm
def fname(request):
...
marketing = MarketingEmails.objects.get(...)
form = EmailForm(instance=marketing)
...
return render(request, 'yourview.html', { 'form': form })
yourview.html
<form action="" method="post">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
{{ field.help_text }}
{% endif %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
How to style model form in django with CSS?
You are right on the point that widget provides you with an option to style your form but it will only style the field for you not the label and any class you mention in the widget should be available in the stlyesheet . you can check the link below it provides a simple example on how you can style your form.
Simple form styling
and if you want to fully style the form with labels and how it should be structured you will have to loop over the form.
below I have mentioned a simple code that illustrates how you can structure your form using django forms
<style>
.h-100{
min-height:100vh;
}
</style>
<div class="w-100 d-flex justiy-content-center align-items-center h-100" >
<form method="POST" class="row" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="col-6 text-start"> {{field.label}} </div>
<div class="col-6"> {{field}} </div>
{% endfor %}
<button type="submit">submit</button>
</form>
i hope this helps you in your problem :)
How to style mixed django form better
Assuming you're using the crispy template pack for styling, you could create a model form class and give the programs
field initial "options" from the database, using a query from whatever model you're storing the "options" on. Here's an example, using some assumptions about your database schema:
class ProgramForm(forms.ModelForm):
class Meta:
fields = ['program']
model = MyRecord
def __init__(self, *args, **kwargs):
super(ProgramForm, self).__init__(*args, **kwargs)
self.fields['program'].queryset = Option.objects.filter(some_field=True).order_by("option_name")
Using this kind of solution, you're using your backend model form class to handle passing the "option" data, and doing all your styling in the html with crispy. Note that if you're using two separate forms, pass them to your template with different names, like:
{{form.klient|as_crispy_field}}
{{program_form.program|as_crispy_field}}
Additionally, you can use Django's widgets to add functionality to your options selector, for example if you wanted checkboxes instead of a dropdown select (ForeignKey vs M2M, let's say).
If you can do none of that and must use this HTML structure and backend approach, you can still target the form with CSS, for example something like:
<style>
#this-label span {
margin-right: 100px;
}
</style>
<label for="{{ form.trn.id_for_label }}" id="this-label"> <span>Trn:</span> </label>
...will add space to the right of "Trn:". This is just one way of doing that, but you could add a class to the span element and target multiple such tags.
Related Topics
Is Quoting the Value of Url() Really Necessary
Difference Between Normalize.Css and Reset Css
How to Style the ≪Option≫ With Only Css
Difference Between Margin and Padding
Order Columns Through Bootstrap4
Set Size on Background Image With Css
Difference Between "Screen" and "Only Screen" in Media Queries
How to Style Child Components from Parent Component'S CSS File
Z-Index Is Canceled by Setting Transform(Rotate)
Remove Blue Border from CSS Custom-Styled Button in Chrome
How to Make an HTML Link Look Like a Button
Opacity CSS Not Working in Ie8
Purpose of Asterisk Before a CSS Property
Bootstrap 4 Navbar With 2 Rows
Why Don't :Before and :After Pseudo Elements Work With 'Img' Elements
Is the CSS Star Selector Considered Harmful (And Why)
Why Does Applying a Css-Filter on the Parent Break the Child Positioning