[Solved]-Using reverse() in django forms

14👍

The problem might be that the form is defined before the urls have been loaded.

Django 1.4 will have a reverse_lazy feature that would solve this problem. You could implement it in your project yourself (see changeset 16121).

Alternatively, you could set the widget in your forms __init__ method instead. Then the reverse call happens when the form is created, after the urls have loaded.

class WorkForm(forms.Form):
    # ...
    subcategory = forms.ChoiceField(
        required=True,
        label=_('SubCategory'),
        help_text=_('Which subcategory suits your work best.')
    )
    def __init__(self, *args, **kwargs):
        super(WorkForm, self).__init__(*args, **kwargs)
        self.fields['subcategory'].widget=DependantChoiceWidget(
            default_value=_('Select category first'),
            data_source_url=reverse('works-json-categories'),
            depends_on='category_id'
        ),

Leave a comment