A ChoiceField whose choices are a model QuerySet.
| 1466 | |
| 1467 | |
| 1468 | class ModelChoiceField(ChoiceField): |
| 1469 | """A ChoiceField whose choices are a model QuerySet.""" |
| 1470 | |
| 1471 | # This class is a subclass of ChoiceField for purity, but it doesn't |
| 1472 | # actually use any of ChoiceField's implementation. |
| 1473 | default_error_messages = { |
| 1474 | "invalid_choice": _( |
| 1475 | "Select a valid choice. That choice is not one of the available choices." |
| 1476 | ), |
| 1477 | } |
| 1478 | iterator = ModelChoiceIterator |
| 1479 | |
| 1480 | def __init__( |
| 1481 | self, |
| 1482 | queryset, |
| 1483 | *, |
| 1484 | empty_label="", |
| 1485 | required=True, |
| 1486 | widget=None, |
| 1487 | label=None, |
| 1488 | initial=None, |
| 1489 | help_text="", |
| 1490 | to_field_name=None, |
| 1491 | limit_choices_to=None, |
| 1492 | blank=False, |
| 1493 | **kwargs, |
| 1494 | ): |
| 1495 | # Call Field instead of ChoiceField __init__() because we don't need |
| 1496 | # ChoiceField.__init__(). |
| 1497 | Field.__init__( |
| 1498 | self, |
| 1499 | required=required, |
| 1500 | widget=widget, |
| 1501 | label=label, |
| 1502 | initial=initial, |
| 1503 | help_text=help_text, |
| 1504 | **kwargs, |
| 1505 | ) |
| 1506 | if (required and initial is not None) or ( |
| 1507 | isinstance(self.widget, RadioSelect) and not blank |
| 1508 | ): |
| 1509 | self.empty_label = None |
| 1510 | else: |
| 1511 | if empty_label == "": |
| 1512 | empty_label = get_blank_choice_label() |
| 1513 | self.empty_label = empty_label |
| 1514 | self.queryset = queryset |
| 1515 | self.limit_choices_to = limit_choices_to # limit the queryset later. |
| 1516 | self.to_field_name = to_field_name |
| 1517 | |
| 1518 | def validate_no_null_characters(self, value): |
| 1519 | non_null_character_validator = ProhibitNullCharactersValidator() |
| 1520 | return non_null_character_validator(value) |
| 1521 | |
| 1522 | def get_limit_choices_to(self): |
| 1523 | """ |
| 1524 | Return ``limit_choices_to`` for this form field. |
| 1525 |
no outgoing calls