从管理面板的选择字段中删除所选选项

Remove the selected option from the choice field in admin panel

如果选择一次,我想减少管理面板中的选择选项。

admin.py

class MyModelForm(forms.ModelForm):
    LOC = [('op1', 'op1'), ('op2', 'op2'),...]

    location = forms.ChoiceField(choices=LOC)


class DataModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    list_display = ('location',)
    search_fields = ['location']

    def get_ordering(self, request):
        return ['location']


admin.site.register(DataModel, DataModelAdmin)

model.py

class DataModel(models.Model):
    location = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.location

我正在尝试这样做,但它会在重新启动服务器时删除所选选项

如果我对你的问题的解释正确,你想从字段选择中删除对象的位置...

class MyModelForm(forms.ModelForm):
    LOC = [('op1', 'op1'), ('op2', 'op2')]

    location = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance:
            self.fields['location'].choices = [
                choice for choice in self.LOC
                if choice[0] != self.instance.location
            ]
        else:
            self.fields['location'].choices = self.LOC

实际上在第二次阅读时,您可能正在寻找 filter

from django.contrib.admin import SimpleListFilter

class LocationFilter(SimpleListFilter):
    title = 'location'
    parameter_name = 'location'

    def lookups(self, request, model_admin):
        locations = DataModel.objects.values_list('location', flat=True)
        return locations

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(location=self.value())

然后将 list_filter = (LocationFilter,) 添加到您的管理员 class。

通过将 init 添加到 MyModelForm class,您可以删除选择字段中的选项

def __init__(self, *args, **kwargs):
    super(MyModelForm, self).__init__(*args, **kwargs)
    item = [i.location for i in DataModel.objects.all()]
    if self.instance.id:
        item.remove(self.instance.location)
    self.fields['location'].choices = [(i, j) for i, j in self.LOC if i not in item]