Задать вопрос

Тел: +7 965 3737 888





Modify fields created by form_for_model

<p>Using newforms you can create forms from existing models easily and automatically with either form_for_model(class) or form_for_instance(instance). Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field.</p>
<p>You can also set the default selection when instantiating the form. In this example, if acct is not contained in the 'account' field choices, the selection defaults to the first entry.</p>
<p>This example is probably not good practice when using form_for_instance because the existing value 'selection' of the choice field is lost and must be reset manually (see above).</p>

Вопрос полезен? Да0/Нет0

Ответы (2):

Ответ полезен? Да0/Нет0

The code

FormClass.base_fields['account'] = forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True))

has the side affect of losing any labeling magic that the model is doing for you (e.g. internationalization of the label). An alternative is to do

    FormClass.base_fields['account'].choices = [(a.id, str(a)) for a in Account.objects.filter(is_active=True)]

Ответ полезен? Да0/Нет0

micampe, it's not better because filter parameters can be part of the user input.