2

Hi I am trying to use a Django plugin called django-countries to add a select with all the countries, sofar It's working but how can I add a html class to the select?

1 Answers1

4

In Django, a form field is rendered into an HTML representation using a widget.

Typically, you can make the widget render class and other HTML attributes by specifying these as arguments to the widget when you are defining your form. For example:

from django import forms

class CommentForm(forms.Form):
    comment = forms.CharField(
        widget=forms.Textarea(attrs={"class": "my-class"})
    )

Given your question relates to a custom field in django-countries you should try the same by passing your custom attributes when instantiating a CountrySelectWidget instance. For example:

from django import forms
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget

class CustomForm(forms.Form):
    country = CountryField().formfield(
        widget=CountrySelectWidget(
           attrs={"class": "my-class"}
        )
    )
lukewarm
  • 839
  • 6
  • 14