开发者

How to set choices in dynamic with Django choicefield?

开发者 https://www.devze.com 2023-02-10 20:58 出处:网络
I want to set choices in dynamic. I used __set_choices method b开发者_如何转开发ut, when request method is POST,

I want to set choices in dynamic.

I used __set_choices method b开发者_如何转开发ut, when request method is POST, is_valid method always return False.

if request.method=='POST':
    _form = MyForm(request.POST)
    if _form.is_valid():
        #something to do


I often set the choices dynamicly in the constructor:

class MyForm(BaseForm):
    afield = forms.ChoiceField(choices=INITIAL_CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['afield'].choices = my_computed_choices


The key is to realise that choices can be any iterable:

import uuid
from itertools import count
class MyForm(BaseForm):

    counter = count(1)

    @staticmethod
    def my_choices():
        yield (uuid.uuid1, next(counter)) 

    afield = forms.ChoiceField(choices=my_choices)

Or whatever logic you like inside my_choices.


In a view you could do the following

--views.py

lstChoices = _getMyChoices()

form.fields['myChoiceField'].choices = lstChoices

where lstChoices is list of dynamically generated tuples for your choices.


Use the constructor to set dynamic choices as shown below:

class DateForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Write the code here to set dynamic choices

        self.fields['month'].choices = dynamic_choices

In addition, I recommend to add the empty label '("", "---------")' to dynamic choices so that the dynamic choices works properly as the default behavior of the select box in Django.


Similar to maersu's solution, but if you have a ModelForm with a model that has a ForeignKey to another model, you may want to assign to the field's queryset instead of choices.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号