Is it possible to limit a choicefield in a form instance in Django
I have a form which contains a choicefield called level allowing the selection of value between 0-3 who's options I want to "limit" dynamically. Is this possible?
pseudo-code for the view would contain something like this:
form = new instance of myform allowed_level = 2 form.level maximum value =< allowed_level
Sure, you can dynamically set the validation criteria when creating the form: (beware: this isn't a complete example as I'm not sure of your setup)
class MyForm(forms.Form): level = ... def __init__(self, *args, **kwargs, allowed_level=None): self.allowed_level = allowed_level super(MyForm, self).__init__(*args, **kwargs) def clean_level(self): data = self.cleaned_data['level'] # Here you can play with what you want to allow if level > self.allowed_level: raise forms.ValidationError("A problem with level value") return data
and just use your view normally
def my_view(request, ...): form = MyForm(allowed_level=2) if form.is_valid(): ...