Django admin - how to change selection in strings?

How can I change the field selection in the Inlines class? I cannot use formfield_for_choice_field in Inlines, so what to use? I have to generate it in admin, because I need to pass the request.

+3
source share
3 answers

if your field is IntegerField or Charfield with a selection attribute, you can override the formfield_for_choice_field method in your built-in class with something like this:

class YourInline(admin.StackedInline): # or TabularInline
    model = YourModelName

    def formfield_for_choice_field(self, db_field, request=None, **kwargs):
        if db_field.name == 'YOUR_FIELD_NAME':
            kwargs['choices'] = (('', '---------'), ('1', 'Choice1'), ('2', 'Choice2'))
        return db_field.formfield(**kwargs)

luck

+4
source

eos87. . , . , :

def clean_fields(self, exclude=None):
    exclude.append('YOUR_FIELD_NAME') # we will do our own validation on this field
    super(YOUR_MODEL, self).clean_fields(exclude = exclude)

    value = self.YOUR_FIELD_NAME
    if value and not self.validChoice(value):
        msg = 'Select a valid choice. %s is not one of the available choices.'
        errors = {''YOUR_FIELD_NAME'': ([msg % value])}
        raise ValidationError(errors)

def validChoice(self, value):
  # add your validation code here
+1

in my case, the form option should be filled out, hope someone helps.

# admin.py
class YourInlineForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
        model = YourModelName
        widgets = {
            'level': forms.widgets.Select(
                choices = (
                    (0,'A'),
                    (1,'B'),
                    (2,'C'),
                ),
            )
        }

# admin.py
class YourInline(admin.StackedInline): # or TabularInline
    model = YourModelName
    form = YourInlineForm

    def formfield_for_choice_field(self, db_field, request=None, **kwargs):
        if db_field.name == 'YOUR_FIELD_NAME':
            kwargs['choices'] = (('', '---------'), ('1', 'Choice1'), ('2', 'Choice2'))
        return db_field.formfield(**kwargs)
+1
source

All Articles