How can I add an attribute to each option in a django model form containing a foreign key?

407 views
Skip to first unread message

Jonathan Dan

unread,
Dec 15, 2014, 12:28:57 PM12/15/14
to django...@googlegroups.com
Hello,

I have two models:

class Currency(models.Model):
...
available = models.BooleanField()

class Offer(models.Model):
...
currency = models.ForeignKey('Currency')

I make a form from the Offer model:

class OfferForm(ModelForm):
class Meta:
model = Offer

How can I add an attribute tag with the value `currency.available` to
each `<option>` from the `<select>` `Currency` widget?

(I am also open to solutions using external apps (like
django-crispy-forms))

(This question has also been asked on stackoverflow:
http://stackoverflow.com/q/27474719/1011154 )

Best regards
Jonathan Dan

Vijay Khemlani

unread,
Dec 15, 2014, 3:03:55 PM12/15/14
to django...@googlegroups.com
If the crispy form is using the usual render methods of Django you can subclass the Select class (in forms/widgets.py), reimplement the "render_option" method and add the parameter to the returned HTML, then you can set the widget attribute of the form field to your created class.

I don't know whether django crispy forms provides a better alternative


Jonathan Dan

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/548F19D8.7010101%40student.tudelft.nl.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages