5

I don't know if I am trying the impossible but I have HTML select option that comes from Django's forms.Form's queryset, States.objects.all().

Model:

class Countries(models.Model):
    name = models.CharField(max_length=25)

Model:

class States(models.Model):
    country_id = models.ForeignKey('Countries')
    name = models.CharField(max_length=25)

Form:

class sign_up_form_school(forms.Form):
    states = forms.ModelChoiceField(
        queryset = States.objects.all(), 
        widget=forms.Select(attrs={
          'class': states.country_id.name #is this POSSIBLE?
          }))

I want each select option value to have different class as I have tried above but it returns error: name 'states' is not defined.

Yax
  • 2,127
  • 5
  • 27
  • 53
  • Good question. Not related but I might point out that your form is a class, so you should follow python class naming convention, like `class SignUpSchoolForm`. – Shang Wang Aug 04 '15 at 12:51
  • I personally don't think it's possible on the form level, but you can use javascript to dynamically add class name to the form, which I don't think would be too hard. – Shang Wang Aug 04 '15 at 12:57

1 Answers1

2

I think this answer will also be answer to your problem: Django form field choices, adding an attribute You would just need to add class instead of title and change rendering a bit.

Community
  • 1
  • 1
Flaiming
  • 413
  • 2
  • 14
  • 2
    No. It doesn't. It is an entirely different thing from what I want to achieve. – Yax Aug 05 '15 at 04:07