10

I have a model that has a field named "state":

class Foo(models.Model):
    ...
    state = models.IntegerField(choices = STATES)
    ...

For every state, possible choices are a certain subset of all STATES. For example:

if foo.state == STATES.OPEN:     #if foo is open, possible states are CLOSED, CANCELED
    ...
if foo.state == STATES.PENDING:  #if foo is pending, possible states are OPEN,CANCELED
    ...

As a result, when foo.state changes to a new state, its set of possible choices changes also.

How can I implement this functionality on Admin add/change pages?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
shanyu
  • 9,536
  • 7
  • 60
  • 68

5 Answers5

18

When you create a new admin interface for a model (e.g. MyModelAdmin) there are specific methods for override the default choices of a field. For a generic choice field:

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == "status":
            kwargs['choices'] = (
                ('accepted', 'Accepted'),
                ('denied', 'Denied'),
            )
            if request.user.is_superuser:
                kwargs['choices'] += (('ready', 'Ready for deployment'),)
        return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)

But you can also override choices for ForeignKey and Many to Many relationships.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
slamora
  • 697
  • 10
  • 17
13

You need to use a custom ModelForm in the ModelAdmin class for that model. In the custom ModelForm's __init__ method, you can dynamically set the choices for that field:

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        current_state = self.instance.state
        ...construct available_choices based on current state...
        self.fields['state'].choices = available_choices

You'd use it like this:

class FooAdmin(admin.ModelAdmin):
    form = FooForm
Carl Meyer
  • 122,012
  • 20
  • 106
  • 116
  • What happens on the 'add' views for the admin, since there's no self.instance, you can't depend on the instance for filtering, it would be nice to have the request object there – Jj. Jul 28 '09 at 02:03
  • Yes, this ModelForm would need to handle the absence of self.instance and set the initial available choices appropriately. I don't know why the request object is relevant, but you do have access to it in ModelAdmin.add_view (http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L704). – Carl Meyer Jul 28 '09 at 14:08
  • Is it possible to change choices in model itself? After all, choices ARE initially specified in the model, when creating the field. – Ivan Vučica Jun 06 '12 at 12:47
  • Yes, you could do a similar thing in an overridden model init method instead. The question just asked about how to do it in the admin. – Carl Meyer Jun 07 '12 at 20:49
  • @CarlMeyer hi, i have a question related to populating the choices inside admin.py , is it possible to have like : `form = form1 list_editable = ('status') fields = ( 'field1', 'field2')` inside the class. Where field2 choices are the one that needs to be initially changed ? I have created this question [question_link](http://stackoverflow.com/questions/36161531/django-foreignkey-show-data-from-postgresql) and now after researching came to this one :) Thanks – crazy_ljuba Mar 23 '16 at 17:08
  • @CarlMeyer Found out what was the problem , nvm – crazy_ljuba Mar 24 '16 at 10:27
0

This seems like a job for some javascript. You want the list of items in a select box to change depending on the value of something else, which is presumably a checkbox or radio button. The only way to make that happen dynamically - without getting the user to save the form and reload the page - would be with javascript.

You can load custom javascript in a model's admin page by using the ModelAdmin's Media class, documented here.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 2
    No, he's trying to set the choices for the next value of a field based on the current value of that same field - a key difference. So changing the options dynamically client-side is not relevant; in fact it would be very confusing. – Carl Meyer May 14 '09 at 22:32
-1

By overriding formfield_for_choice_field(), you can modify choices for Django Admin without creating a custom "forms.ModelForm" as shown below:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == "status":
            kwargs['choices'] = (
                ('accepted', 'Accepted'),
                ('denied', 'Denied'),
            )
            if request.user.is_superuser:
                kwargs['choices'] += (('ready', 'Ready for deployment'),)
        return super().formfield_for_choice_field(db_field, request, **kwargs)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
-1

I see what you're trying to do, but why not just display all of them and if the person picks the (already set) current state, just don't change anything?

you could also just build a view with a form to provide this functionality

Jiaaro
  • 74,485
  • 42
  • 169
  • 190
  • that's a possibility, however not a very-elegant and secure one. changing the state triggers some calculations and modifications of the data to be made, therefore I really don't want to trust users, even if they are admins. – shanyu May 14 '09 at 20:08