Define CSS Class in Django Forms

Define css class in django Forms

Answered my own question. Sigh

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

I didn't realize it was passed into the widget constructor.

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.

Setting css class to field in form depending of it's type

you can use the django form that is inherited from modelform to define specific css class to the form fields.

for instance,
models.py file:

class Post(models.Model):
title=models.CharField(max_length=254)
text=models.TextField()

forms.py file

from . import models 
class PostForm(forms.ModelForms):
class Meta():
model=models.Post
fields='__all__'
widgets={
'title':forms.TextInput(attrs={'class':'textinputclass'}), #--->> you can use this textinputclass as the css class in your css file to style the title field of your forms.
'text':forms.Textarea(attrs={'class':'content'})
}

now in your static>css>yourcss.css you can access the class that we defined above as normal css class.

.content{
font-size:15px;
}

How to add css for both label and input field in django from form.py

You don’t have to let Django unpack the form’s fields; you can do it manually if you like. Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. As you unpack the form with form.as_p you can add your css classes like :

<p><label class="my-classes" for="{{ form.name.id_for_label }}">Name:</label>
{{ form.name }}</p>
<p><label class="my-classes" for="{{ form.address.id_for_label }}">Address:</label>
{{ form.address}}</p>
<p><label class="my-classes" for="{{ form.mobile.id_for_label }}">Mobile:</label>
{{ form.mobile}}</p>

[docs]

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.

how can I add css class to a django form field that is generated by RelatedFieldWidgetWrapper

The way of setting style for inputs in forms is widgets. you can try this:

def __init__(self, *args, **kwargs):
super(StudentProfileForm, self).__init__(*args, **kwargs)
self.fields['guardian'].widget.attrs['class'] = 'selectpicker'

How to add a CSS class to Django registration password form

In the attrs , add "id" field so that you can access the fields with their id and then you can apply css in that .

class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email', 'password1', 'password2', 'password')
widgets = {
'username': TextInput(attrs={
'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black",
'placeholder': "Username",
'id' : "id_register_form_username" ,
}),
'email': EmailInput(attrs={
'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black",
'placeholder': 'Email address' ,
'id' : "id_register_form_email' ,
}),
'password1': PasswordInput(attrs={
'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black",
'type': 'password',
'name': 'password',
'placeholder': 'Password',
'id' : "id_register_form_password1" ,
}),
'password2': PasswordInput(attrs={
'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black",
'placeholder': 'Password'
'id' : "id_register_form_password2" ,
}),
}

Then in your html , just use css using the id .



Related Topics



Leave a reply



Submit